题目来源
题目描述
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
}
};
题目解析
分析题意
-
数据量是 1 0 5 10^5 105,那么时间复杂度是O(N),但是题目算法时间复杂度必须是 O(log n) 级别,所以需要砍一半
-
注意到是有序数组,那么就要想到二分法
-
第二次刷题:少想这些有的没有的,可以直接找target-0.5和target+0.5。
class Solution {
int helper(vector<int>& nums, float target, int low, int high) {
if(low > high){
return low;
}
int mid = low + (high - low) / 2;
if (nums[mid] == target){
return mid;
}if(nums[mid] < target){
return helper(nums, target, mid + 1, high);
}else{
return helper(nums, target, low, high - 1);
}
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
int low = 0, high = nums.size() - 1;
int left = helper(nums, target - 0.5, 0,nums.size() - 1);
int right = helper(nums, target + 0.5, 0,nums.size() - 1);
if(left >= nums.size() || nums[left] != target){
return {-1, -1};
}else{
return {left, right - 1};
}
}
};
- 第一次刷题:
class Solution {
int lessMostRight(vector<int>& arr, int target){
int L = 0, R = arr.size();
int ans = -1;
while (L <= R){
int mid = L + (R - L) / 2;
if(arr[mid] < target){
ans = mid;
L = mid + 1;
}else{
R = mid - 1;
}
}
return ans;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
if(nums.empty()){
return {-1, -1};
}
int L = lessMostRight(nums, target) + 1;
if(L == nums.size() || nums[L] != target){
return {-1, 1};
}
return {L, lessMostRight(nums, target + 1)};
}
};
类似题目
题目 | 思路 |
---|---|
leetcode:34. 在排序数组中查找元素的第一个和最后一个位置 | 二分 |
leetcode:35. 给定有序数组和target,搜索target应该插入的位置 | 二分 |
leetcode:278. 第一个错误的版本 | 二分 |
leetcode:4. 寻找两个正序数组的中位数 | 二分 |