Search for a Range
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]
.
vector<int> searchRange(int A[], int n, int target) {
int low =0,high =n-1,index,start =-1,end =1;
vector<int> vec;
int mid;
while(low<=high)
{
mid =(low+high)/2;
if(A[mid]>target)
{
high =mid-1;
}
else if(A[mid]<target)
{
low =mid +1;
}
else
{
index =mid;
break;
}
}
if(low<=high)
{
start =end =mid;
while(start>=0&&A[--start] ==target);
if(start<0)
{
vec.push_back(0);
}
else
{
vec.push_back(start+1);
}
while(end<=n-1&&A[++end] ==target);
if(end>n-1)
{
vec.push_back(n-1);
}
else
{
vec.push_back(end-1);
}
return vec;
}
else
{
vec.push_back(-1);
vec.push_back(-1);
return vec;
}
}