原题:
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);
int firstBadVersion(int n) {
int l1=1;
int l2=n;
int num=-1;
while(l1<l2)
{
num=(l2-l1)/2+l1;
if(isBadVersion(num))
l2=num;
else
l1=num+1;
}
return l1;
}
想到我上次写的代码那么蠢,也是醉了。这个是copy了一下别人的,我自己写的判断条件太复杂,一直超时。