# Search for a Range

class Solution {
public:
// 记住最后递归的left 和right 能够减少寻找左边界和右边界的时间。
int binarySearch(vector<int> &nums, int left, int right, int target) {
int mid = (left + right) / 2;
if(left > right)
return -1;
if(nums[mid] == target)
return mid;
if(nums[mid] > target)
return binarySearch(nums, left, mid - 1, target);
if(nums[mid] < target)
return binarySearch(nums, mid + 1, right, target);
}
// 设置isRight bool 值来判断是左边界还是有边界。
int binarySearchLR(vector<int> &nums, int left, int right, int target, bool isRight) {
int mid = (left + right) / 2;
if(isRight) {
if(left == right)
return left;
if(nums[mid] == target && nums[mid + 1] != target)
return mid;
else if(nums[mid] == target && nums[mid + 1] == target )
return binarySearchLR(nums, mid + 1, right, target, true);
else
return binarySearchLR(nums, left, mid - 1, target, true);
}
else {
// 这里需要考虑mid - 1是否会越界，因为只有两个元素时，mid总等于left，而如果left是0，则mid - 1会越界
if(left == right || left == right - 1) {
if(nums[left] == target)
return left;
return right;
}
if(nums[mid] == target && nums[mid - 1] != target)
return mid;
else if(nums[mid] == target && nums[mid - 1] == target )
return binarySearchLR(nums, left, mid - 1, target, false);
else
return binarySearchLR(nums, mid + 1, right, target, false);
}
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result{-1, -1};
if(nums.empty())
return result;
int n = nums.size();
int findIndex = binarySearch(nums, 0, n - 1, target);
if(findIndex == -1)
return result;
result[0] = binarySearchLR(nums, 0, findIndex, target, false);
result[1] = binarySearchLR(nums, findIndex, n - 1, target, true);
return result;
}
};
• 本文已收录于以下专栏：

举报原因： 您举报文章：Search for a Range 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)