Binary Search 278 First Bad Version
Regular binary search question, provide python solution below
# first version
32ms
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
first,end=1,n
while True:
mid=first+(end-first)/2
res=isBadVersion(mid)
if res: # if Bad version
##previous one is not Bad, 'mid' proving as first bad then return
if mid==1 or not isBadVersion(mid-1):
return mid
end=mid-1
else:
first=mid+1
这里从first=1开始,避免了后来isBadVersion(mid-1)的会去找比0小的index:
考虑只[1]的情况,first=0,n=1, mid=0;first=1, n=1, mid=1.
# Second Version
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
first,end = 1,n
while first + 1 < end:
mid = first + (end - first) / 2
# 这里不断缩小bad version的范围
if isBadVersion(mid):
end = mid
else:
first = mid
# 直到最后剩下两个element,再对比哪个是bad version.
if isBadVersion(first):
return first
return end