目录
统一记忆为闭区间,只需要修改nums[mid]==target时收缩哪边边界,以及越界情况
最基本的二分搜索
def binary_search(nums:List[int],target:int):
left=0
right=len(nums)-1
while(left<=right):
mid=left+(right-left)//2
if nums[mid]<target:
left=mid+1
elif nums[mid]>target:
right=mid-1
else:#mid所在位置的值等于target
return mid
return -1
寻找左边界的二分搜索
def left_bound(nums:List[int],target:int):
left=0
right=len(nums)-1
while(left<=right):
mid=left+(right-left)//2
if nums[mid]<target:
left=mid+1
elif nums[mid]>target:
right=mid-1
else:#mid所在位置的值等于target
right=mid-1#收缩右侧边界,锁定右边界
#检查left越界情况
if left>=len(nums) or nums[left]!=target:
return -1
return left
寻找右边界的二分搜索
def right_bound(nums:List[int],target:int):
left=0
right=len(nums)-1
while(left<=right):
mid=left+(right-left)//2
if nums[mid]<target:
left=mid+1
elif nums[mid]>target:
right=mid-1
else:#mid所在位置的值等于target
left=mid+1#收缩左侧边界,锁定右边界
#检查right越界情况
if right<0 or nums[right]!=target:
return -1
return right
标签:二分,right,target,nums,mid,搜索,模板,left
From: https://www.cnblogs.com/lushuang55/p/18056047