一、朴素二分
. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/binary-search/description/
int left = 0, right = nums.size();while (left <= right) {int mid = left + ((right - left) >> 1); // 防止溢出if (nums[mid] == target) {return mid;} else if (nums[mid] > target) {right = mid - 1;} else {left = mid + 1;}}return -1;
二、整数二分
. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/description/
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {// 寻找左区间右端点,右区间左端点int l = 0, r = nums.size() - 1;vector<int> ans = {-1, -1};if (nums.size() == 0) return ans;while (l < r) {int mid = l + (r - l) / 2;if (nums[mid] >= target) r = mid;else l = mid + 1;}if (nums[l] == target) ans[0] = l;else return ans;r = nums.size() - 1;while (l < r) {int mid = l + (r - l + 1) / 2;if (nums[mid] <= target) l = mid;else r = mid - 1;}ans[1] = l;return ans;
}
};