边工作边刷题:70天一遍leetcode: day 58-1
First Bad Version
要点:本质上就是>=的bounded binary search,因为在某一点之后都是bad version,目标是找到起点。
错误点:
-
=并不是(low+high+1)/2,low=mid的情况才是,也就是<=或者<(策略:面试中还是只提low+(high-low)/2,如果面试官有考点,那一定是会提示,然后再顺水推舟)
# 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
"""
low,high=1,n
mid = low+(high-low)/2
while low<high:
if isBadVersion(mid):
high=mid
else:
low=mid+1
mid = low+(high-low)/2
return mid