easy,二分即可,记得在扩大范围时判断是否越界。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
//有序+logn=二分,因为有可能有多个相同数字,所以在找到target之后left--,right++,直到找到区间
if(nums.size() == 0) return vector<int>{-1,-1};
int left = 0, right = nums.size()-1;
while(left <= right){
int mid = left + (right-left)/2;
if(nums[mid] == target){
left = mid;
right = mid;
//当退出循环的时候已经是不等于的了
while(left-1 >= 0 && nums[left-1] == nums[mid]){
left--;
}
while(right +1 < nums.size() && nums[right+1] == nums[mid]){
right++;
}
return vector<int>{left,right};
}
if(nums[mid] < target){
left = mid+1;
}
else{
right = mid-1;
}
}
return vector<int>{-1,-1};
}
};
找到某个数,就往左右找,判断的是left>=0且nums[left]==target的情况下才-1。最后得到的left和right都是不满足要求的,所以left+1,right-1
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
//查找logn=二分
//用二分找到这个数后就往前往后找到开始结束就行了,如果没找到就return-1-1
int left = 0, right = nums.size()-1;
//要找某个数,就是严格大于才能退出
while(left <= right){
int mid = left + (right-left)/2;
if(nums[mid] == target){
left = mid;
right = mid;
while(left >= 0 && nums[left] == target) left--;
while(right <= nums.size()-1 && nums[right] == target) right++;
//此时left和right都已经是不等于情况下了
return vector<int>{left+1,right-1};
}
else if(nums[mid] < target){
left = mid+1;
}
else{
right = mid-1;
}
}
return vector<int>{-1,-1};
}
};
一定要记得l和r在退出线性检测后是不符合要求的!!
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
//找到某个值后线性探测,具体找某个值,l<=r
int l = 0, r = nums.size()-1;
while(l <= r){
int mid = l + (r-l)/2;
if(nums[mid] == target){
l = mid;
r = mid;
while(l >=0 && nums[l] == nums[mid]) l--;
while(r < nums.size() && nums[r] == nums[mid]) r++;
//此时的l和r都不符合要求了
return vector<int>{l+1,r-1};
}
else if(nums[mid] < target){
l = mid+1;
}
else{
r = mid-1;
}
}
return vector<int>{-1,-1};
}
};