Question
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.
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.
思路
要做到减少判断的次数,最先想到的是二分法,不断取中值进行判断,缩小搜索范围。如果mid
是bad version
那么mid
可能是第一个bad version
,所以将右边界缩小到mid
;如果mid
不是bad version
,那么first bad version
一定在mid
右侧,所以将左边界缩小至mid
左侧,这里left = mid+1
很重要。举个例子:
还剩两个值,比如1, 2时,因为(1+2)//2 == 1
,所以此时mid
为1,假设1不是bad version
, left = mid
还是等于1,将会陷入死循环。
最后范围被压缩到一个值,这个值就是The first bad version
。
Code
1 | class Solution(object): |