Given an array of integers nums
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]
.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
题目:有序数组的目标数对应的区间上下范围。
思路:二分查找。参考Discuss。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0) return {-1, -1};
int l = 0, r = n-1;
while(l < r){
int mid = l + (r-l)/2;
if(nums[mid] > target)
r = mid - 1;
else if(nums[mid] < target)
l = mid + 1;
else
r = mid;
}
if(nums[l] != target)
return {-1, -1};
vector<int> res(2);
res[0] = l;
r = n-1; // 找右侧边界时l不用赋值为0
while(l < r){
int mid = l + (r-l)/2 + 1; // 注意这里多加了1
if(nums[mid] > target)
r = mid - 1;
else if(nums[mid] < target)
l = mid + 1;
else
l = mid;
}
res[1] = r;
return res;
}
};
另可参考解法2
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0) return {-1, -1};
double left = target - 0.5, right = target + 0.5;
int l = binarySearch(nums, left);
int r = binarySearch(nums, right);
if(l == r) return {-1, -1};
return {l, r-1};
}
private:
int binarySearch(const vector<int>& nums, double target){
int n = nums.size();
int l = 0, r = n-1;
while(l <= r){
int mid = l + (r - l)/2;
if(target > nums[mid])
l = mid + 1;
else
r = mid - 1;
}
return l;
}
};