题目链接 https://leetcode.com/problems/first-bad-version/description/
思路分析:这是一道最基础的,经典的利用二分法的题目。思考模式应该分一下三个步骤:
1.数据的类型是,前一半符合条件,后一半不服后,模型是 OOXX;
2.我们的目标是找到一个X,使得它满足它的前一个是O(或者空);
3.每当我们找到一个X时,更新end的位置为X
代码实现如下:
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int start =1 , end = n ;
int mid =start ,res;
if(isBadVersion(start)) return start; //XXXXXX && only 1 vesion case
while(start +1 < end){
mid =start +(end-start)/2 ; // OOOXXX or OOO case , start is right version.
//‘left + right’ may cause the Integer Overflow, meaning that left+right > 2147483647
if(isBadVersion(mid))
end = mid ;
else
start = mid; // since we have check if first start is right vesion , we can assume every start is right
}
if(isBadVersion(start)) return start;
if(isBadVersion(end)) return end; // XXXXXX && only 2 vesion case
}