新的挑战开始了!!!
Day1-First Bad Version
问题描述
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.
就是给了一个数字,这个数字表示的意思是软件更新的最后一个版本号,但是这个软件之前有一个版本是坏的,而在那之后的版本都是坏的,为此需要我们找到第一个坏的版本,题中给了一个查询版本是否是坏的API,让我们尽量少的调用这个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.
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
#二分搜索,例子都给出解法了吧。。
start = 1
end = n
while start <= end:
mid = (start + end) // 2
if isBadVersion(mid):
end = mid - 1
else:
start = mid + 1
return start
时间复杂度为O(logn),在leetcode上这个解法的排名还是挺低的。我也好奇还有什么解法,所以去leetcode中的discuss中找到了下面这种解法,但是看不出来比二分搜索能高多少。。。
class Solution:
def firstBadVersion(self, n):
if isBadVersion(1): return 1
b = [1,n]
while 1:
m, i, j = (b[0]+b[1])//2, b[0], b[1]
b = [m,j] if isBadVersion(i) == isBadVersion(m) else [i,m]
if j - i == 1: return j