You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n
versions [1, 2, ..., n]
and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version)
which will return whether version
is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
思路:二分法
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int high=n,low=1,ver;
while(low<high){
ver=low+(high-low)/2;//原来写的是(high-low)/2,这样子好像会溢出造成超时……虽然我也不知道为什么会溢出……
//其实大家写的都是(low+high)/2……那么我上面写的本来就不对噗
if(isBadVersion(ver))high=ver;
else low=ver+1;//这里要注意加一呐
}
return low;
}
};