思路:看到O(logn)的时间复杂度,很容易想到使用二分查找,不过要注意一下边界问题,分别查找开始位置和结束位置。
class Solution {
public:
int left_bound(vector<int>&nums, int target) {
int left = 0, right = nums.size() - 1;
// 搜索区间为 [left, right]
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
// 搜索区间变为 [mid+1, right]
left = mid + 1;
} else if (nums[mid] > target) {
// 搜索区间变为 [left, mid-1]
right = mid - 1;
} else if (nums[mid] == target) {
// 收缩右侧边界
right = mid - 1;
}
}
// 检查left出界情况
if (left >= nums.size() || nums[left] != target)
return -1;
return left;
}
int right_bound(vector<int>&nums, int target) {
int left = 0, right = nums.size() - 1;
//搜索区间[left,right]
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
//搜索区间变为[mid+1,right]
left = mid + 1;
} else if (nums[mid] > target) {
//搜索区间变为[left,right-1]
right = mid - 1;
} else if (nums[mid] == target) {
// 收缩左侧边界
left = mid + 1;
}
}
// 检查 right 越界的情况
if (right < 0 || nums[right] != target)
return -1;
return right;
}
vector<int> searchRange(vector<int>& nums, int target) {
int left=left_bound(nums,target);
int right=right_bound(nums,target);
vector<int>res={left,right};
return res;
}
};