解题思路
二分查找,找到目标后,start向左找左边界,end向右找右边界,若数组中不存在目标元素则返回两个-1.算法复杂度可能不满足O(logn)
代码
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
int low = 0,high = n - 1;
int start = -1,end = -1;
while(low <= high){
int mid = (low + high) / 2;
if(A[mid] > target)
high = mid - 1;
else if(A[mid] < target)
low = mid + 1;
else{
start = end = mid;
while(start >= 0 && A[start] == A[mid])
start--;
while(end < n && A[end] == A[mid])
end++;
break;
}
}
vector<int>res;
if(start == -1 && end == -1){
res.push_back(-1);
res.push_back(-1);
}
else{
res.push_back(start + 1);
res.push_back(end - 1);
}
return res;
}
};