Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1,
-1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> res;
res.clear();
if (n<=0) {
res.push_back(-1);
res.push_back(-1);
return res;
}
int L = 0, R = n - 1, M;
while(L <= R) {
M = (L + R) / 2;
if (A[M] > target) {
R = M - 1;
}
else if(A[M] < target) {
L = M + 1;
}
else {
break;
}
}
if (A[M] != target) {
res.push_back(-1);
res.push_back(-1);
}
else {
L = 0, R = M - 1;
int mid;
while(R>=0 && A[R]==target) {
mid = (L + R) / 2;
if (A[mid] < target) {
L = mid + 1;
}
else if(A[mid] >= target) {
R = mid - 1;
}
}
res.push_back(R + 1);
L = M + 1,R = n - 1;
while(L<n && A[L] == target) {
mid = (L + R) / 2;
if (A[mid] <= target) {
L = mid + 1;
}
else {
R = mid - 1;
}
}
res.push_back(L-1);
}
return res;
}
};