给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
方案一:
指定一高一低两个指针,低指针向后遍历,高指针向前遍历,最终低指针指向起始位置,高指针指向结束位置。时间复杂度O(n)。
class Solution {
/**
*@param A : an integer sorted array
*@param target : an integer to be inserted
*return : a list of length 2, [index1, index2]
*/
public:
vector<int> searchRange(vector<int> &A, int target) {
// write your code here
int low = 0;
int high = A.size() - 1;
vector<int> ans;
while(low < A.size()){
while(low < A.size() && A[low] != target) low ++;
while(0 < high && A[high] != target) high --;
if (low < A.size()){
ans.push_back(low);
ans.push_back(high);
return ans;
}
}
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
};
方案二:
二分查找。
class Solution {
/**
*@param A : an integer sorted array
*@param target : an integer to be inserted
*return : a list of length 2, [index1, index2]
*/
public:
vector<int> searchRange(vector<int> &A, int target) {
// write your code here
int low = lower_bound(A.begin(), A.end(), target) - A.begin();
int high = upper_bound(A.begin(), A.end(), target) - A.begin();
vector<int> ans;
if(low == high){
low = -1;
high = 0;
}
ans.push_back(low);
ans.push_back(high - 1);
return ans;
}
};