LeetCode OJ-34.Search for a Range
题目描述
Given an array of integers sorted in ascending order, 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]
.
题目理解
在有序数组中,寻找到值为target的元素的范围(可能有多个元素值为target)。直接遍历可以解决问题,但题目要求了时间复杂度要为O(logn),如此就不能直接遍历了。不过看到O(logn)就该联想到二分查找了,所以这题可以直接使用二分查找来做了。
思路是这样的,二分查找一般只用来查找一个元素,本题需要求解的是范围,所以这题应该这样处理,找到元素后,判断对应的索引位置是否小于所寻找的range的起始位置,或者大于range的结束位置,如果是,则更新起始和结束位置。具体代码如下:
Code
static void divide(const vector<int> &nums, int first, int last,
int target, int &start, int &end)
{
if (first == last) {
if (nums[first] == target) {
if (first < start) {
start = first;
}
if (first > end) {
end = first;
}
}
return ;
}
int mid = (first + last) / 2;
if (nums[mid] < target) {
divide(nums, mid + 1, last, target, start, end);
}
else if (nums[mid] > target) {
divide(nums, first, mid, target, start, end);
}
else {
divide(nums, first, mid, target, start, end);
divide(nums, mid + 1, last, target, start, end);
}
}
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res;
if (nums.size() == 0) { // 判断是否为空
res.push_back(-1);
res.push_back(-1);
return res;
}
int start = (int) nums.size() + 1;
int end = -1;
divide(nums, 0, (int) (nums.size() - 1), target, start, end);
if (end == -1) { // 未找到对应范围
res.push_back(-1);
res.push_back(-1);
return res;
}
res.push_back(start);
res.push_back(end);
return res;
}
};