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]
.
Solution:
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> res;
int left = 0, right = n - 1, pos;
while(left <= right)
{
int mid = (left + right) / 2;
if(A[mid] == target)
{
pos = mid;
break;
}
else if(A[mid] < target) left = mid + 1;
else right = right - 1;
}
if(left > right)
{
res.push_back(-1);
res.push_back(-1);
return res;
}
left = right = pos;
while(--left >= 0)
{
if(A[left] != A[pos]) break;
}
left++;
while(++right < n)
{
if(A[right] != A[pos]) break;
}
right--;
res.push_back(left);
res.push_back(right);
return res;
}
};