题目描述:
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))。
思路:此题采用二分法。因为需要找到一个范围,所以需要找到目标值的最小坐标和最大坐标。我们对二分法做一些细节改动,分两次查找(分别保持最小坐标min_index和最大坐标max_index),并返回结果。
假设数组长度为n,时间复杂度为O(log(n))。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size();
vector<int> ans;
// Exceptional Case:
if(n == 0){
ans = {-1, -1};
return ans;
}
// binary search
// find the minimum valid index
int min_index = -1;
int left = 0, right = n - 1;
while(left <= right){
int mid = (left + right) >> 1;
if(nums[mid] >= target){
if(nums[mid] == target){
min_index = mid;
}
right = mid - 1;
}
else if(nums[mid] < target){
left = mid + 1;
}
}
// debug
// cout << "left: " << left << endl;
if(min_index == -1){
ans = {-1, -1};
return ans;
}
// find the maximum valid index
int max_index = -1;
left = 0, right = n - 1;
while(left <= right){
int mid = (left + right) >> 1;
if(nums[mid] > target){
right = mid - 1;
}
else if(nums[mid] <= target){
if(nums[mid] == target){
max_index = mid;
}
left = mid + 1;
}
}
// debug
// cout << "right: " << right << endl;
ans = {min_index, max_index};
return ans;
}
};