About Binary Search about Binary Search 二分查找普通的二分查找123456789101112131415int BinarySearch_nonrecursive(vector<int>& nums, int target) { int left = 0, right = (int)nums.size() - 1; while (left <= right) { //不加 = 如果数组长度为1 会错 int mid = (left + right)/2; if (nums[mid] > target) { right = mid - 1; } else if (nums[mid] < target) { left = mid + 1; } else return mid; } return 0;} 123456789//递归 int BinarySearch_recursive(vector<int>& nums, int target, int left, int right) { if (left > right) return 0; int mid = (left + right) / 2; if (nums[mid] > target) return BinarySearch_recursive(nums, target, left, mid - 1); else if (nums[mid] < target) return BinarySearch_recursive(nums, target, mid + 1, right); else return mid; } 如果你只想要二分查找找到的第一个:12345678910111213int BinarySearch_First_nonrecursive(vector<int>& nums, int target) { //查找第一个 int left = 0, right = (int)nums.size() - 1; while (left <= right) { int mid = (left + right)/2; if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return nums[left] == target ? left : -1;} (l + r + 1) >> 1; 进阶的 (r - l)/2 + l; #Programming #Algorithm About Binary Search https://www.mementos.top/1976/04/01/about Binary Search 二分查找/ 作者 Natsumi 发布于 1976年4月1日 许可协议 VSCode Debug 上一篇 About Bit Manipulation (Bit-Twiddling) 下一篇