1 基本二分搜索
【区间】:[left, right]
【终止条件】:left = right + 1
int binarySearch(vector<int>& nums, int target) {
// 区间[left, right]
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
else if (nums[mid] > target)
right = mid - 1;
}
return -1;
}
2 左侧边界二分
【区间】:[left, right)
【终止条件】:left = right
/**寻找左侧边界的二分搜索**/
int leftBound(vector<int>& nums, int target) {
// 区间[left, right)
int left = 0, right = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target)
// 不返回,收缩右边界,找到左侧边界
right = mid;
else if (nums[mid] < target)
left = mid + 1;
else if (nums[mid] > target)
right = mid;
}
if (left == nums.size()) return -1;
return nums[left] == target ? left : -1;
}
3 右侧边界二分
【区间】:[left, right)
【注意】:最后是mid = left - 1
【终止条件】:left = right
/**寻找右侧边界的二分搜索**/
int rightBound(vector<int>& nums, int target) {
// 区间[left, right)
int left = 0, right = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target)
// 不返回,收缩左边界,找到左右侧边界
left = mid + 1;
else if (nums[mid] < target)
left = mid + 1;
else if (nums[mid] > target)
right = mid;
}
if (left == 0) return -1;
return nums[left - 1] == target ? left - 1 : -1;
}
4 总结
致谢
感谢labudadong大佬的整理,以此学习