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]
.
2014年2月21日
自己编写的代码,直接从头开始找,找到大了就break,小的就++
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> v={-1,-1};
int i=0;
while(i<n){
if(A[i]<target)
i++;
else if(A[i]>target){
if(v[0]!=-1){
v[1]=i-1;
}
break;
}
else if (A[i]==target){
if(v[0]==-1){
v[0]=i;
}
i++;
}
}
if(v[0]!=-1 &&v[1]==-1)
v[1]=n-1;
return v;
}
};
参考网上的解答
用二分查找的方法,先查最左边匹配项,再查最后边匹配项
也可以用 递归实现
int firstLeft(int A[], int n, int target){
if(n==0)
return -1;
int left=0;
int right= n-1;
while(left < right){
int mid=left+(right-left)/2;
if(A[mid]<target)
left=mid+1;
else
right=mid;
}
if(A[left]==target)
return left;
else
return -1;
}
int firstRight(int A[], int n, int target){
if(n==0)
return -1;
int left = 0;
int right = n - 1;
while( left <= right ){
int mid = left + (right - left)/ 2;
if(A[mid]<=target)
left=mid+1;
else
right=mid-1;
}
if(A[right]==target)
return right;
else
return -1;
}
vector<int> searchRange(int A[], int n, int target) {
vector<int> v(2);
v[0]=firstLeft(A,n,target);
v[1]=firstRight(A,n,target);
return v;
}