问题:
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]
.
这道题要求时间要控制在O(log n)内,就是暗示我们要使用二分的方法来解决问题。但是它又是叫我们找两个边界,所以一个直接的思路就是通过二分查找先找到目标值的位置,然后再向左向右找边界。这样每次都是筛掉一半,时间要求肯定可以满足。
代码如下:
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int start = 0, end = nums.size() - 1;
vector<int> res;
int ans_start = -1, ans_end = -1;
//判断特殊情况
if( nums.size() == 0 ){
res.push_back(-1);
res.push_back(-1);
return res;
}
if (nums[start] == target) {
ans_start = 0;
}
if (nums[end] == target) {
ans_end = end;
}
//开始搜索目标值的大概位置
while (start <= end) {
int mid = (start + end) / 2;
if (nums[mid] == target) {
if (ans_start == -1) {
ans_start = findStart(nums, target, start, mid);//找开始的边界
}
if (ans_end == -1) {
ans_end = findEnd(nums, target, mid , end);//找结束的边界
}
break;
}
else if (nums[mid] > target) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
if (ans_start == -1 && ans_end == -1) {//假若不存在目标值
res.push_back(-1);
res.push_back(-1);
return res;
}
res.push_back(ans_start);
res.push_back(ans_end);
return res;
}
int findStart(vector<int>& nums, int target, int start, int end) {
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (nums[mid] < target) {
start = mid + 1;
}
else if (nums[mid - 1] != target) {
break;
}
else {
end = mid - 1;
}
}
return mid;
}
int findEnd(vector<int>& nums, int target, int start, int end) {
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (nums[mid] > target) {
end = mid - 1;
}
else if (nums[mid + 1] != target) {
break;
}
else {
start = mid + 1;
}
}
return mid;
}
};