给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
给出[5, 7, 7, 8, 8, 10]
和目标值target=8
,
返回[3, 4]
思路:二分查找
class Solution {
public:
/*
* @param A: an integer sorted array
* @param target: an integer to be inserted
* @return: a list of length 2, [index1, index2]
*/
vector<int> searchRange(vector<int> A, int target) {
vector<int> result;
int size = A.size()-1;
if(A.empty()) {
result.push_back(-1);
result.push_back(-1);
}
else {
result.push_back(getFirstTarget(A, target, 0, size));
result.push_back(getLastTarget(A, target, 0, size));
}
return result;
}
//找左边界
int getFirstTarget(vector<int> &A, int target, int low, int high){
if(low > high)
return -1;
int mid = (low+high)/2;
if(A[mid] == target) {
if((mid>0 && A[mid-1]!=target) || mid==0)
return mid;
else
high = mid-1;
}
else if(A[mid] > target)
high = mid-1;
else
low = mid+1;
return getFirstTarget(A, target, low, high);
}
//找右边界
int getLastTarget(vector<int> &A, int target, int low, int high){
int size = A.size()-1;
if(low > high)
return -1;
int mid = (low+high)/2;
if(A[mid] == target) {
if((mid<size && A[mid+1]!=target) || mid==size)
return mid;
else
low = mid+1;
}
else if(A[mid] > target)
high = mid-1;
else
low = mid+1;
return getLastTarget(A, target, low, high);
}
};