给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
给出[5, 7, 7, 8, 8, 10]和目标值target=8,
返回[3, 4]
题目链接:http://www.lintcode.com/zh-cn/problem/search-for-a-range/
通过二分查找找到起始位置和结束位置,一定要考虑到数组为空的情况,不然A[i-1]会产生runtime error
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> res = {-1,-1};
if (A.empty()) return res;
int i = 0,j = A.size();
while (i < j) {
int mid = (i + j) / 2;
if (A[mid] >= target) j = mid;
else i = mid + 1;
}
if (A[j] == target) res[0] = j;
i = 0,j = A.size();
while (i < j) {
int mid = (i + j) / 2;
if (A[mid] > target) j = mid;
else i = mid + 1;
}
if (A[i - 1] == target) res[1] = i - 1;
return res;
}
};