二分查找要求顺序存储结构。
1. 二分查找的框架
递归
def BinarySearch(arr,left,right,target):
if left < = right:
mid = (left+right) //2
// mid = int(1+(r-l)/2)
if arr[mid] == x:
return mid
// 若元素小于mid,只需要比较左边区域
elif arr[mid]>target:
right = mid-1
return BinarySearch(arr,left,right,target)
// 若元素大于mid,则只需要比较右边元素
elif arr[mid]<target:
left = mid+1
return BinarySearch(arr,left,right,target)
else:
return -1 // 不存在
2. 寻找一个数target
存在一个有序数组[1,2,3,3,3,5,6,6,7],target=3,返回索引2,若想得到右侧边界即索引4
3. 查找左侧边界
target
元素在数组中重复,输出最左侧元素的下标
int left_bound(int[] nums, int target) {
if (nums.length == 0) return -1;
int left = 0;
int right = nums.length-1
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
right = mid -1; // 缩小搜索范围 // 注意
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
}
}
// 循环退出:left=right+1
return left; // 注意
}
4. 查找右侧边界
target
元素在数组中重复,输出最右侧元素的下标
int right_bound(int[] nums, int target) {
if (nums.length == 0) return -1;
int left = 0;
int right = nums.length-1;
while (left < right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
left = mid+1; // 注意
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid -1;
}
}
return right; // 注意
}