First bad version

Catalogue
  1. 1. Question
  2. 2. 思路
  3. 3. Code

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.

思路

要做到减少判断的次数,最先想到的是二分法,不断取中值进行判断,缩小搜索范围。如果midbad 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 versionleft = mid还是等于1,将会陷入死循环。

最后范围被压缩到一个值,这个值就是The first bad version

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left = 1
right = n
while left != right:
mid = (left+right)//2
if isBadVersion(mid):
right = mid
else:
left = mid+1 # mid is not the first bad version
return left
Comments