leetcode 刷题-二分查找

  1. [69]x的平方根
class Solution:
    def mySqrt(self, x: int) -> int:
        #优化,二分查找
        left=0 #初始
        right=x #边界
        ans = -1 #边界,ans在此题中一定有解
        while left <= right:
            mid = (left+right)//2
            if mid*mid <= x:
                ans = mid
                left = mid+1
            else: 
                right = mid-1
        return ans 
  1. [209]长度最小的子数组
class Solution:
   def minSubArrayLen(self, target: int, nums: List[int]) -> int:
       # 暴力法,把所有子数组的和先计算出来,超出内存限制
       # 暴力法,遍历start,每次遍历end直到len(nums)-1,超出时间限制
       # 将遍历end改为二分查找
       ans = len(nums)+1
       sums = [nums[0]] #初始化
       for i in range(1,len(nums)):
           sums.append(sums[-1] + nums[i])    
       for start in range(0,len(nums)):
           if start == 0:
               target2 = target
           else:    
               target2 = target + sums[start - 1] 
           #递增查找大于target的end值,二分查找,时间复杂度LogN
           bound = bisect.bisect_left(sums, target2)
           if bound != len(sums): #上述函数找不到的化返回的是sums数组的长度
               ans = min(ans,bound-start+1)
       return 0 if ans == len(nums)+1 else ans  
def bisect_left(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e < x, and all e in
    a[i:] have e >= x.  So if x already appears in the list, a.insert(x) will
    insert just before the leftmost x already there.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        # Use __lt__ to match the logic in list.sort() and in heapq
        if a[mid] < x: lo = mid+1
        else: hi = mid
    return lo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值