1 查找target是否在数组中,没有返回-1
def binarySearch(nums, target): left, right = 0, len(nums) -1 while left <= right: mid = (left + (right - left)) // 2 if nums[mid] > target: right = mid - 1 elif nums[mid] < target: left = mid + 1 else: return mid # 没有就返回-1 return -1
2 查找数组中第一个等于target的index, 没有返回-1
def binarySearch(nums, target): left, right = 0, len(nums) -1 while left <= right: mid = left + (right - left) // 2 if nums[mid] >= target: right = mid - 1 elif nums[mid] < target: left = mid + 1 if left < len(nums) and nums[left] == target: return left # 没有就返回-1 return -1
查找最后一个等于target下标,没有返回-1
while left <= right: mid = left + (right - left) // 2 if nums[mid] > target: right = mid - 1 elif nums[mid] <= target: left = mid + 1 if right >= 0 and nums[right] == target: return right # 没有就返回-1 return -1
查找第一个大于等于target的小标,没有返回-1
while left <= right: mid = left + (right - left )// 2 if nums[mid] > target: right = mid - 1 elif nums[mid] <= target: left = mid + 1 if left < n: return left else: return -1
查找最后一个小于等于value的下标
结尾判断改为 while left <= right: mid = left + (right - left )// 2 if nums[mid] >= target: right = mid - 1 elif nums[mid] < target: left = mid + 1 if right >= 0: return right else: return -1
总结
所有的区间均为左闭右闭 [left, right]
- 如果是找左边界,将等号挂在right分支上, 最后判断left
- 如果是找右边界,将等号挂在left分支上, 最后判断right
非直接查找
- 如果找大于目标的左边界,将等号挂在left分支,最后判断 left是不是 < len(nums)
- 如果找小于目标的右边界,将等号挂在right分支,最后判断right是不是 >= 0
这个总结直接进行记忆