题目:
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 haven
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 APIbool isBadVersion(version)
which will return whetherversion
is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Example:Given n = 5, and version = 4 is the first bad version. call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version.
解释:
很明显,对于这种搜索问题,就该用二分查找做。
python代码:
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left=1
right=n
while left<right:
mid=left+(right-left)/2
if isBadVersion(mid):
right=mid
else:
left=mid+1
return left
c++代码:
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int left=1,right=n;
while(left<right)
{
int mid=left+(right-left)/2;
if (isBadVersion(mid))
right=mid;
else
left=mid+1;
}
return left;
}
};
总结:
注意二分查找的细节是<
和right=mid
,事实上是如果一个更新条件是=
,那么如果这个时候把=
写入循环判断中,有可能陷入死循环,因为到达临界点时,条件显示是更新right
,而right
却永远不会更新,所以会死循环。
最后返回left还是right无所谓了,因为最后它们肯定是相等的。