二分查找总结
前提:排序数组,无重复元素
1.写法有两种:左闭右闭、左闭右开
2.左闭右闭:
(1) while条件为left <= right,因为是闭区间,所以右边界是有意义的
(2) mid初始计算为(数组长度 - 1)对2整除
(3) if nums[mid] > target,右边界更新为 mid -1
class Solution: def search(self, nums: List[int], target: int) -> int: left, right = 0, len(nums) - 1 while left <= right: middle = (left + right) // 2 if nums[middle] < target: left = middle + 1 elif nums[middle] > target: right = middle - 1 else: return middle return -1
3.左闭右开:
(1) while条件为left < right,因为是开区间,右边界无意义
(2) mid初始计算为数组长度 对2整除
(3) if nums[mid] > target,右边界更新为mid
class Solution: def search(self, nums: List[int], target: int) -> int: left,right =0, len(nums) while left < right: mid = (left + right) // 2 if nums[mid] < target: left = mid+1 elif nums[mid] > target: right = mid else: return mid return -1
重点难点:区间边界的处理