Leetcode 278 First Bad Version 二分查找(二分下标)

题意:找到第一个出问题的版本

二分查找,注意 mid = l + (r - l + 1) / 2;因为整数会溢出

 1 // Forward declaration of isBadVersion API.
 2 bool isBadVersion(int version);
 3 
 4 class Solution {
 5 public:
 6     int firstBadVersion(int n) {
 7         int l = 1, r = n , ans ;
 8         while(l <= r){
 9             int mid = l +  (r - l + 1) / 2;
10             if(!isBadVersion(mid)){
11                 l = mid + 1;
12             }
13             else {
14                 r = mid - 1;
15                 ans = mid;
16             }
17         }
18         return ans;
19     }
20 };

 

posted @ 2016-05-07 21:47  Breeze0806  阅读(152)  评论(0编辑  收藏  举报