Search for a Range(范围搜索)
【难度:Medium】
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(log n).
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].
给定一有序数组和目标值,在数组中查找目标值出现的区间范围,复杂度要求为O(log n)内,若无目标值则区间为[-1,-1]。
解题思路
二分查找的变型,思想是通过二分查找找到nums[mid] == target出现的位置mid,从mid向两边搜索,向左为start,向右为end,直到出现非target或越界的情况,回退一步,就是target出现的区间[start,end]。
c++代码如下:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans;
int low = 0;
int high = nums.size()-1;
while (low <= high) {
int mid = (low+high)/2;
if (nums[mid] > target) {
high = mid-1;
} else if (nums[mid] < target) {
low = mid+1;
} else {
//出现目标值
int start = mid;
int end = mid;
//向左搜索
while (start >= 0 && nums[start] == target)
start--;
//回退
if (start < 0 || nums[start] != target)
start++;
//向右搜索
while (end < high && nums[end] == target)
end++;
//回退
if (end > high || nums[end] != target)
end--;
ans.push_back(start);
ans.push_back(end);
return ans;
}
}
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
};