First Bad Version
给出一个数组,如果有一个数字是badversion,则其后的数字都是badversion。要求找出第一个出现badversion的位置。
按顺序查找会超时,用二分法就可以轻松过了。
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
long left=1, right=n, mid;
while( left <= right ){
mid = (left+right)/2;
if(isBadVersion(mid)){
right = mid - 1;
}else{
left = mid + 1;
}
}
if(isBadVersion(left))
return left;
else
return right;
}
};