二分查找
1. 使用条件
- sorted(单调递增或递减)
- Bounded(存在上下界)
- Accessible by index(能够通过索引访问)
2. 应用场景
找一个数,寻找左侧边界、寻找右侧边界
3. leetcode——704. 二分查找
def binarysearch(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right-left) // 2
print(mid)
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
4.leetcode69——实现sqrt函数
二分法。因为 y = x 2 y = x^2 y=x2的图像曲线是单调递增的。二分法的下界是n,上界是0。
def mySqrt(self, x: int) -> int:
left = 0
right = x
while left<=right:
mid = left + (right - left)/2
cal = mid * mid
if int(cal) == x:
return int(mid)
elif cal < x:
left = mid
else:
right = mid