二分搜索常用【转载】
转自:https://www.cnblogs.com/grandyang/p/6854825.html
1.查找和目标值完全相等的数
int find(vector<int>& nums, int target) { int left = 0, right = nums.size(); while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < target) left = mid + 1; else right = mid; } return -1; }
这里给出了一个总结,关于right、循环条件、return的这些控制。
对于我来说的话,我还是比较喜欢,第二套?比较习惯,right=len(nums)-1这样,那么之后right=mid-1,return也是right-1,while循环的话需要等号。
2.寻找左边界
转自:https://labuladong.gitee.io/algo/2/18/28/
// 搜索左侧边界 int left_bound(int[] nums, int target) { if (nums.length == 0) return -1; int left = 0, right = nums.length; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { // 当找到 target 时,收缩右侧边界 right = mid; } else if (nums[mid] < target) { left = mid + 1; } else if (nums[mid] > target) { right = mid; } } return left; }
3.寻找右边界
// 搜索右侧边界 int right_bound(int[] nums, int target) { if (nums.length == 0) return -1; int left = 0, right = nums.length; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { // 当找到 target 时,收缩左侧边界 left = mid + 1; } else if (nums[mid] < target) { left = mid + 1; } else if (nums[mid] > target) { right = mid; } } return left - 1; }