LeetCode 278. The first wrong version (python)

Topic Link

Subject description:

You are a product manager, he is currently leading a team to develop new products. Unfortunately, the latest version of your product did not pass quality inspection. Since the previous version of the development of each version is based, so all later versions of the wrong version is wrong.

Suppose you have n versions [1, 2, ..., n], you want to find out first of all lead to the wrong version after version error.

You can call bool isBadVersion (version) interfaces to determine whether the version number version error in unit tests. Implement a function to find the first incorrect version. You should try to reduce the number of API calls.

Example:

Given n = 5, and a first version = 4 is the wrong version.

Call isBadVersion (3) -> false
calls isBadVersion (5) -> true
calling isBadVersion (4) -> true

So 4 is the first wrong version.

Problem-solving ideas:

Dichotomy, if a bad version, indicating the boundary on the left, so that end equal to mid, if the current version is a good value, indicating the boundary on the right, so that is equal to begin mid + 1

# 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
        """
        begin,end=1,n
        while begin<end:
            mid=(begin+end)//2
            if isBadVersion(mid):#是坏版本,边界在左边
                end=mid
            else:
                begin=mid+1#不是坏版本,边界在右边
        return begin

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44740082/article/details/91549247