https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
//左闭右开
int length = nums.size();
if(length == 0) return {-1,-1} ;
vector<int> res;
//搜索左位置
int left = 0;
int right= length-1;
// left取值[0,length]
while(left<=right){
int mid = left +(right-left)/2;
if(target == nums[mid]){
right = mid-1;
}
else if(target > nums[mid]){
left = mid+1;
}
else{
right = mid-1;
}
}
//数组越界检查
int res1 = 0;
if(left == length || nums[left] != target ) res1 = -1;
else{
res1 = left ;
}
if(res1 == -1) return {-1,-1} ;
res.push_back(res1);
//搜索右位置
left = 0;
right= length-1;
while(left<=right){
int mid = left +(right-left)/2;
if(target == nums[mid]){
left = mid+1;
}
else if(target > nums[mid]){
left = mid+1;
}
else{
right = mid -1;
}
}
int res2 = 0;
// 检查越界 ,right[-1,length-1]
if(right == -1 || nums[right] != target) res2 =-1;
else{
res2 = right;
}
res.push_back(res2);
return res;
}
};
网友评论