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.
方法
采用二分查找
注意求middle的方法,应该使用middle = left+(right-left)/2;
,不要用middle = (left+right)/2;
,后者会溢出,leetcode平台会报Time Limit Exceeded
c代码
#include <assert.h>
//Forward declaration of isBanVersion API.
int isBadVersion(int version);
int firstBadVersion(int n) {
int left=1, right=n;
int middle;
while(left<right) {
// middle = (left+right)/2;
middle = left+(right-left)/2;
if(isBadVersion(middle))
right = middle;
else
left = middle+1;
}
return left;
}
int isBadVersion(int version) {
return version>=3 ? 1 : 0;
}
int main() {
assert(firstBadVersion(10) == 3);
return 0;
}