使用两次二分查找,一次查找 target 的开始位置,一次查找结束位置,时间复杂度 O ( log n ) O(\log n) O(logn) ,空间复杂度 O ( 1 ) O(1) O(1) :
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0)
return vector<int>{-1, -1};
if(n == 1)
return nums[0] == target ? vector<int>{0, 0} : vector<int>{-1, -1};
int l = 0, r = n - 1, midl = -1, midr = -1, tmp;
while(l <= r) {
tmp = (l + r) / 2;
if(nums[tmp] == target) {
midl = tmp;
r = tmp - 1;
}
else if(target < nums[tmp])
r = tmp - 1;
else l = tmp + 1;
}
l = 0;
r = n - 1;
while(l <= r) {
tmp = (l + r) / 2;
if(nums[tmp] == target) {
midr = tmp;
l = tmp + 1;
}
else if(target < nums[tmp])
r = tmp - 1;
else l = tmp + 1;
}
return vector<int>{midl, midr};
}
};