class Solution {
public:
void binarySearch(vector<int>& nums, int target, int left, int right, int& l, int& r){
if(left > right)
return;
int mid = (left+right)/2;
if(nums[mid] == target){
if(mid < l) l=mid;
if(mid > r) r=mid;
binarySearch(nums,target,mid+1,right,l,r);
binarySearch(nums,target,left,mid-1,l,r);
}else if(nums[mid] < target)
binarySearch(nums,target,mid+1,right,l,r);
else
binarySearch(nums,target,left,mid-1,l,r);
}
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.empty()) return vector<int>{-1,-1};
int l=nums.size(),r=0;
binarySearch(nums,target,0,nums.size()-1,l,r);
if(l==nums.size() && r==0)
return vector<int>{-1,-1};
else
return vector<int>{l,r};
}
};
34. 在排序数组中查找元素的第一个和最后一个位置/C++
最新推荐文章于 2024-09-27 21:14:08 发布