标准二分搜索
// 标准二分法
int BinarySearch (vector<int> nums, int target)
{
if (nums.empty()) {
return -1;
}
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int mid = (right - left) / 2 + left;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
}
}
return -1;
}
搜索左边界
// 搜索左边界
int left_bound(vector<int> nums, int target)
{
if (nums.length == 0)
return -1;
int left = 0;
int right = nums.length - 1; // 注意,左右均闭,搜索区间为[left, right]
while (left <= right) { // 注意, 退出循环条件为left == right + 1;
int mid = (left + right) / 2;
if (nums[mid] == target) { // 别返回,收缩右侧边界,锁定左侧边界
right = mid - 1;
} else if (nums[mid] > target) {
right = mid - 1; // 注意
} else if (nums[mid] < target) {
left = mid + 1;
}
}
// 当target大于nums中所有元素时,注意left可能越界
if (left >= nums.length || nums[left] != target) {
return -1;
}
return left;
}
搜索右边界
// 搜索右边界
int right_bound(vector<int> nums, int target)
{
if (nums.length == 0)
return -1;
int left = 0;
int right = nums.length - 1; // 注意,左右均闭,搜索区间为[left, right]
while (left <= right) { // 注意, 退出循环条件为right = left - 1;
int mid = (left + right) / 2;
if (nums[mid] == target) { // 别返回,收缩左侧边界,锁定右侧边界
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1; // 注意
} else if (nums[mid] < target) {
left = mid + 1;
}
}
// 当target小于nums中所有元素时,注意right可能越界
if (right < 0 || nums[left] != target) {
return -1;
}
return right;
}