Search for a Range
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,那么使用二分查找,而且查找的是一个范围。正好利用STL 中的 lower_bound(),upper_bound()。
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> res;
int *l=lower_bound(A,A+n,target); //如不存在,则返回的是target应该存在的位置
int *r=upper_bound(A,A+n,target);
if(*l!=target){
res.push_back(-1);
res.push_back(-1);
}
else{
res.push_back(l-A);
res.push_back(r-1-A);
}
return res;
}
};