Search for a Range
Q:
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].
A: 二分查找。二分找出target在数组中出现的第一个位置和最后一个位置。
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int firstPos = -1;
int lastPos = -1;
firstPos = searchFirst(A,n,target);
if(firstPos!=-1)
lastPos = searchLast(A,n,target);
vector<int> res;
res.push_back(firstPos);
res.push_back(lastPos);
return res;
}
int searchFirst(int A[],int n,int target)
{
int b=0,e=n-1;
int m;
while(b<e)
{
m = b+(e-b)/2;
if(A[m]<target)
b = m+1;
else
e = m;
}
if(A[b]==target)
return b;
else return -1;
}
int searchLast(int A[],int n,int target)
{
int b=0,e=n-1;
int m;
while(b<e)
{
m = b+(e-b+1)/2;
if(A[m]>target)
e = m-1;
else
b = m;
}
if(A[b]==target)
return b;
else return -1;
}
浙公网安备 33010602011771号