LeetCodeHot100_34——《在排序数组中查找元素的第一个和最后一个位置》
读题思路:理论上其实就是利用二分法遍历数组分别找到二分法左右边界,左边界就是第一个大于等于target的值的下标,右边界是第一个大于target的值的下标减一。
具体代码:
int binarySearch(vector<int>& nums, int target, bool lower) {
int n = nums.size();
int left = 0, right = n - 1, ans = nums.size();
while (left <= right)
{
int mid = (left + right) / 2;
if (nums[mid] > target || (lower && nums[mid] >= target))
{
right = mid - 1;
ans = mid;
}
else {
left = mid + 1;
}
}
return ans;
}
vector<int> searchRange(vector<int>& nums, int target) {
int leftIndex = binarySearch(nums, target, true);
int rightIndex = binarySearch(nums, target, false) - 1;
if (leftIndex<=rightIndex&&rightIndex<nums.size()&&nums[leftIndex]==target&&nums[rightIndex]==target)
{
return vector<int>{leftIndex, rightIndex};
}
return vector<int>{-1, -1};
}