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].
思路:二分法(查找第一个及最后一个target value的下标)
代码:
void searchBinary(int A[], int p, int q,int &first,int &last,int target)
{
if(p<=q)
{
int mid=(p+q)/2;
if(A[mid] == target)
{
if(first > mid)
{
first=mid;
searchBinary(A,p,mid-1,first,last,target);
}
if(last < mid)
{
last=mid;
searchBinary(A,mid+1,q,first,last,target);
}
}
else if(A[mid] < target)
{
searchBinary(A,mid+1,q,first,last,target);
}
else
{
searchBinary(A,p,mid-1,first,last,target);
}
}
}
vector<int> searchRange(int A[], int n, int target)
{
int p=0;
int q=n-1;
vector<int> res;
res.push_back(n);
res.push_back(-1);
int first=n;
int last=-1;
searchBinary(A,p,q,first,last,target);
res[0]=first;
res[1]=last;
if(first==n)
{
res[0]=-1;
}
return res;
}
394

被折叠的 条评论
为什么被折叠?



