Search for a Range
二分
vector<int> searchRange(int A[], int n, int target) {
// Note: The Solution object is instantiated only once and is reused by each test case
vector<int> res(2,-1);
int firstpos = findFirstPos(A,0,n-1,target);
if(firstpos!=-1){
int lastpos = findLastPos(A,0,n-1,target);
res[0] = firstpos;
res[1] = lastpos;
}
return res;
}
int findFirstPos(int A[], int begin,int end, int target)
{
int mid;
while(begin<end)
{
mid = begin + (end-begin)/2;
if(A[mid]<target)
begin = mid+1;
else
end = mid;
}
return (A[begin]==target?begin:-1);
}
int findLastPos(int A[],int begin,int end,int target)
{
int mid;
while(begin<end)
{
mid = begin+(end-begin+1)/2;
if(A[mid]>target)
end = mid-1;
else
begin = mid;
}
return (A[begin]==target?begin:-1);
}
浙公网安备 33010602011771号