题目:
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.
题意:
现在有n个版本的产品,已知从某个版本产品坏了之后,后面的版本产品都是坏的。写一个函数,找出第一个产品坏掉的版本。已知有个接口函数isBadVersion(n)可以用来判断第n个版本产品是好的还是坏的,要求尽量少地调用接口函数isBadVersion(n).
代码:
# 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
"""
if isBadVersion(1) == True : #先判断第一个版本是不是坏的
return 1
else : #如果第一个版本是好的,开始二分查找第一个坏的版本
low = 1 #low:标记好的产品的版本
high = n #high:标记坏的产品的版本
while low < high :
temp = (low+high)/2 #找中点
if isBadVersion(temp) == True : #如果中点是坏的版本,则将high移到中点
high = temp
if isBadVersion(temp) == False : #如果中点是好的版本,则将low移到中点
low = temp
if low + 1 == high : #如果好、坏版本挨着了,则退出循环
break
return high #返回第一个坏的版本
笔记:
与普通的二分查找中high = temp-1,low = temp+1 有点不同,具体问题要具体分析