二分查找
找边界点
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int low=1;
int high=n;
int flag=n;
while(low<=high){
int mid=low+(high-low)/2;
if(!isBadVersion(mid)) low=mid+1;
else{
if(mid<=flag) flag=mid;
high=mid-1;
}
}
return flag;
}
};
更简洁一点:
注意此时的判断条件是low<high
而不是low<=high
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int low=1;
int high=n;
while(low<high){
int mid=low+(high-low)/2;
if(!isBadVersion(mid)) low=mid+1;
else{
high=mid;
}
}
return high;
}
};