# Search for a Range

32人阅读 评论(0)

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;
}
};
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：188次
• 积分：41
• 等级：
• 排名：千里之外
• 原创：4篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档
阅读排行