给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
例1:
输入:
[]
9
输出:
[-1,-1]
例2:
输入:
[5, 7, 7, 8, 8, 10]
8
输出:
[3, 4]
挑战
时间复杂度 O(log n)
寻找两次,第一次寻找左边界,再一次寻找右边界
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)
{
// write your code here
vector<int> ret;
ret.push_back(left_bound(A, target));
ret.push_back(right_bound(A, target));
return ret;
}
int left_bound(vector<int>& nums, int target)
{
if (nums.size() == 0)
return -1;
int left = 0;
int right = nums.size(); // 注意
while (left < right) { // 注意
int mid = (left + right) / 2;
if (nums[mid] == target) {
right = mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid; // 注意
}
}
return nums[left] == target ? left : -1;
}
int right_bound(vector<int>& nums, int target)
{
if (nums.size() == 0) return -1;
int left = 0, right = nums.size();
while (left < right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
left = mid + 1; // 注意
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid;
}
}
return nums[left-1] == target ? (left-1) : -1;// 注意
}
};