Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(logn) .
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
解题思路
思路一:先使用二分搜索查找目标数,若找到则从该位置向两边查找,若没找到则返回[-1,-1]
。该方法不能保证时间复杂度一定是
O(logn)
。
思路二:使用两次二分查找算法分别找到目标数出现的最左端位置和最右端位置。时间复杂度为 O(logn) 。代码如下:
class Solution {
private:
/*
* 查找 target 出现的最左边的位置
*/
int findLeftMost(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while ((nums[left] != target) && (left < right)) {
int middle = (left + right) >> 1;
if (nums[middle] >= target) {
left++;
right = middle;
}
else {
left = middle + 1;
}
}
return nums[left] == target ? left : -1;
}
/*
* 查找 target 出现的最右边的位置
*/
int findRightMost(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while ((nums[right] != target) && (left < right)) {
int middle = (left + right) >> 1;
if (nums[middle] <= target) {
right--;
left = middle;
}
else {
right = middle - 1;
}
}
return nums[right] == target ? right : -1;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left = findLeftMost(nums, target);
int right = findRightMost(nums, target);
vector<int> result({left, right});
return result;
}
};