May LeetCoding Challenge 之 标准二分查找法

使用二分查找法:前提条件为序列有序,经常在以下两种情况下使用

1.在[1,2,3,4,5,6,7]查找一个目标target数字。相比线性遍历时间复杂度O(n),二分查找时间复杂度为O(logn)。

2.在[0,0,0,1,1,1,1]查找元素1第一次出现的位置。

JAVA

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left = 1;
        int right = n;
        while(left < right){
            int mid = left + (right-left)/2;//bug (left+right)/2。这样写会出现溢出情况
            if(isBadVersion(mid)) right = mid;
            else left = mid+1;
        }
        return left;
    }
}

Python3

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

猜你喜欢

转载自www.cnblogs.com/yawenw/p/12823000.html
今日推荐