Loading

278. 第一个错误的版本

题目

 

代码

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int low=1,high=n;
        while(low<=high)
        {
            //这里可能导致溢出
            int mid=low/2+high/2+(low%2+high%2)/2;
            cout<<mid<<endl;
            if(isBadVersion(mid))
            {
               if(isBadVersion(mid-1)==false)
                    return mid;
                else
                {
                    high=mid-1;
                    continue;
                }
            }
            else
            {
                low=mid+1;
                continue;
            }
        }
        
        
    }
};

 

思路

利用二分查找的思想。

posted @ 2018-09-16 08:14  李正浩  阅读(176)  评论(0编辑  收藏  举报