First Bad Version in python

问题链接

https://leetcode.com/explore/interview/card/top-interview-questions-easy/96/sorting-and-searching/774/

解题思路

利用while循环,左右取均值,进行二分查找:
1、遇到isBadVersion右边界取中值
2、没有遇到则左边界为中值+1
3、最终返回左边界

代码

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

你可能感兴趣的:(First Bad Version in python)