二分查找的典型运用,一段范围为false,一段为true,这个题为寻找false变为true的那个点。注意二分查找的边界的处理,还有while里面的条件 。
二分查找小技巧:(left + right) / 2 可能相加会溢出,所以应该这样(right - left) / 2 + left。
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int left, right, mid;
left = 1;
right = n;
while(left + 1 < right)
{
mid = (right - left) / 2 + left;
if(isBadVersion(mid))
right = mid;
else
left = mid;
}
if(isBadVersion(left))
return left;
else
return right;
}
};