/*这道题本质上是考二分搜索。解题思路为:
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
最新推荐文章于 2022-07-27 13:46:02 发布