难度中等:34. 在排序数组中查找元素的第一个和最后一个位置
思路
利用二分法,找到最左边的target,然后将target+1,用同样的方法
也可以找最右边的target,只是注意right和left的变化区别。
代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.size()==0)
return {-1,-1};
int left =0;
int right = nums.size()-1;
while(left < right ){
int mid = (left + right) / 2;
if(nums[mid] == target ){
right = mid ;
}else if (nums[mid] < target){
left = mid+1;
}else{
right = mid ;
}
}
int a = left;
left =0;
right = nums.size()-1;
while(left < right ){
int mid = (left + right) / 2;
if(nums[mid] == target+1 ){
right = mid ;
}else if (nums[mid] < target+1){
left = mid+1;
}else{
right = mid ;
}
}
int b = left;
if(nums[a]!=target)
return {-1,-1};
if(nums[b]!=target)
return {a,b-1};
return {a,b};
}
};