/*这道题本质上是考二分搜索。解题思路为:
1.先用二分搜索找到数组中需要查找数字的下标;
2.从给下标向左右扩展,获取它最左最右的下标并返回结果。*/
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left, right, idx;
idx = binarySearch(nums, target);
if(idx == -1){
left = -1;
right = -1;
}
else{
int i = idx;;
while(i >= 0 && nums[i] == target) --i;
left = i+1;
while(idx < nums.size() && nums[idx] == target) ++idx;
right = idx-1;
}
vector<int> res;
res.push_back(left);
res.push_back(right);
return res;
}
int binarySearch(const vector<int> &nums, int target){
int left(0), right(nums.size()-1);
while(left <= right){
int mid = (left + right) / 2;
if(nums[mid] == target) return mid;
else if(nums[mid] < target) left = mid+1;
else right = mid-1;
}
return -1;
}
};LeetCode之Search for a Range
最新推荐文章于 2018-01-16 21:58:41 发布
本文介绍了一种使用二分搜索算法解决寻找目标元素在有序数组中最左和最右位置的问题。通过实现`binarySearch`函数定位目标元素,再扩展获取其确切范围。
337

被折叠的 条评论
为什么被折叠?



