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]
.
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
//二分查找 找到后左右展开
int i,left,right,mid;
vector<int> res;
left=0;right=n-1;
while(left<=right)
{
mid=left+(right-left)/2;
if(A[mid]<target)
left=mid+1;
else if(A[mid]>target)
right=mid-1;
else
{
for(i=mid;i>0;i--)
{
if(A[i-1]!=A[i])
break;
}
res.push_back(i);
for(i=mid;i<n-1;i++)
{
if(A[i+1]!=A[i])
break;
}
res.push_back(i);
return res;
}
}
res.push_back(-1);
res.push_back(-1);
return res;
}
};