12.26 2014
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 begin=0;
int end=n-1;
int pos=-1;
vector<int> range;
range.push_back(-1);
range.push_back(-1);
while(begin<=end){
int mid=(begin+end)/2;
if(target==A[mid]){
pos=mid;
break;
}
else if(target>A[mid])
begin=mid+1;
else
end=mid-1;
}
if(pos==-1)
return range;
int index=pos;
while(A[index]==target && index>=0){
index--;
}
range[0]=index+1;
index=pos;
while(A[index]==target && index<=n-1){
index++;
}
range[1]=index-1;
return range;
}
};
总结:
先二分查找,找到其中一个target以后,向前后遍历寻找相同的值。最后前后组成range