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) {
if(n<=0)
return 0;
int r1=1,r2=n;
while(r1<r2){
int fir=(r2-r1)/2+r1;
if(isBadVersion(fir)){
r2=fir;
}
else{
r1=fir+1;
}
}
return r1;
}
};
int fir=(r2-r1)/2+r1;将(r2-r1)/2+r1的结果强制转换为int类型。
最后一次判断的时候r1==r2-1,此时的fir=r1,。