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
[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