题目
请点击
思路
- 二分查找法
- 在找到目标元素时,定义i=j=mid,i–寻找第一次出现的位置,j++寻找最后一次出现的位置
代码
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ret(2);
ret[0] = ret[1] = -1;
int size = nums.size();
int left = 0, right = size - 1;
while(left <= right) {
int mid = (left + right) >> 1;
if(nums[mid] > target) right = mid - 1;
else if(nums[mid] < target) left = mid + 1;
else {
int i = mid, j = mid;
while(i >= 0 && nums[i] == target) {
ret[0] = i;
i--;
}
while(j < size && nums[j] == target) {
ret[1] = j;
j++;
}
break;
}
}
return ret;
}
int pos(vector<int>& nums, int target, bool flag){
int size = nums.size();
int left = 0, right = size - 1;
while(left <= right) {
int mid = (left + right) >> 1;
if((flag && nums[mid] >= target) || (nums[mid] > target))
right = mid - 1;
else left = mid + 1;
}
return left;
}
vector<int> searchRange1(vector<int>& nums, int target) {
vector<int> ret(2);
ret[0] = ret[1] = -1;
int pos1 = pos(nums, target, true);
int pos2 = pos(nums, target, false) - 1;
if(pos1 <= pos2 && pos1 >= 0 && pos2 < nums.size()){
ret[0] = pos1;
ret[1] = pos2;
}
return ret;
}
int main(){
vector<int> nums;
nums.emplace_back(1);
int target = 1;
vector<int> ret = searchRange1(nums, target);
cout<<ret[0]<<" "<<ret[1]<<endl;
return 0;
}