【LintCode-二分搜索】 74. First Bad Version
lintcode 74. First Bad Version
url: https://www.lintcode.com/problem/first-bad-version/description
1、题目
Description
The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests. Find the first bad version.
You can call isBadVersion to help you determine which version is the first bad one. The details interface can be found in the code’s annotation part.
Please read the annotation in code area to get the correct way to call isBadVersion in different language. For example, Java is SVNRepo.isBadVersion(v)
Have you met this question in a real interview?
Example
Given n = 5:
isBadVersion(3) -> false
isBadVersion(5) -> true
isBadVersion(4) -> true
Here we are 100% sure that the 4th version is the first bad version.
Challenge
You should call isBadVersion as few as possible.
2、思路
经典的二分搜索
3、python代码实现
class SVNRepo:
bad_version = 1898
@classmethod
def isBadVersion(cls, n):
if n >= cls.bad_version:
return True
else:
return False
class Solution:
"""
@param n: An integer
@return: An integer which is the first bad version.
"""
def findFirstBadVersion(self, n):
if n < 1:
return -1
head = 1
tail = n
mid = head + (tail - head) // 2
while head < tail:
if SVNRepo.isBadVersion(mid):
if mid - 1 != 0 and SVNRepo.isBadVersion(mid - 1):
tail = mid - 1
mid = head + (tail - head) // 2
else:
return mid
else:
if mid + 1 <= n:
head = mid + 1
mid = head + (tail - head) // 2
else:
return mid
return mid
if __name__ == '__main__':
s = Solution()
SVNRepo.bad_version = 1898
n = s.findFirstBadVersion(1899)
print(n)
上一篇: 因为风的缘故(外一首)
下一篇: 双调查找(数组先递增后递减)