First Bad Version

来源:互联网 发布:git 源码安装 编辑:程序博客网 时间:2024/06/04 14:42

leetcode第278题,这道题很明显是二分查找,但是由于误解了所给API的含义,所以造成了一些困扰。

这道题只要注意API的意义,还有就是注意不要遍历出界即可。另外值得注意的是,为什么一开始high要赋值为n+1而不是n,因为如果n与low一开始就相等,则while循环进入不了,为了能使while循环进入,需要作此设置,不过这样并不影响最后的结果。

# 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 = 1        high = n+1        while low < high:            mid = (low+high)//2            if isBadVersion(mid):                high = mid            else:                low = mid + 1        return low            


0 0
原创粉丝点击