LintCode-61.搜索区间
搜索区间
给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]样例
给出[5, 7, 7, 8, 8, 10]和目标值target=8,
返回[3, 4]挑战
时间复杂度 O(log n)
标签
数组 排序数组 二分法
code
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
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);
}
};