LeetCode探索之旅(75)-278第一个错误的数

今天继续刷LeetCode,第278题,求数组中第一个错误的数;

分析:
用最快的方式找到这个数,也就可以最少调用函数。那就是用二分查找来解决问题。

问题:
1、二分查找的变形。

附上C++代码:

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int low=1,high=n;
        while(low<high)
        {
            int mid=low+(high-low)/2;
            if(isBadVersion(mid))
                high=mid;
            else
                low=mid+1;
        }
        return high;
    }
};

附上Python代码:

# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):

class Solution:
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        l=0
        r=n-1
        while l<=r:
            mid=l+(r-l)//2
            if isBadVersion(mid):
                r=mid-1
            else:
                l=mid+1
        return l

猜你喜欢

转载自blog.csdn.net/JerryZengZ/article/details/89308203