当前位置:网站首页>leetcode:81. 搜索旋转排序数组 II
leetcode:81. 搜索旋转排序数组 II
2022-08-02 08:49:00 【OceanStar的学习笔记】
题目来源
题目描述


class Solution {
public:
bool search(vector<int>& nums, int target) {
}
};
题目解析
本题是leetcode:33. 搜索旋转排序数组的扩展,区别在于本题有重复元素。
我们知道,所谓的旋转其实就是「将某个下标前面的所有数整体移到后面,使得数组从整体有序变为分段有序」。
本题元素不唯一,这意味着我们无法直接根据nums[0]的大小关系,将数组分为为两段,即无法通过「二分」来找到旋转点。
因为「二分」的本质是二段性,并非单调性。只要一段满足某个性质,另外一段不满足某个性质,就可以用「二分」。
举个,我们使用数据 [0,1,2,2,2,3,4,5] 来理解为什么不同的旋转点会导致「二段性丢失」:

class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right){
int mid = left + (right - left) / 2;
if(nums[mid] == target){
return true;
}
if(nums[left] == nums[mid]){
left++;
continue; // 跳到下个left
}
if (nums[left] <= nums[mid]) {
// 左侧有序,这里可不用=,因为上面判断了
if (nums[left] <= target && target < nums[mid]) {
// 是否在左侧
right = mid - 1;
} else {
// 否则在右边
left = mid + 1;
}
} else {
// 右侧有序
if (nums[mid] < target && target <= nums[right]) {
// 是否在右侧
left = mid + 1;
} else {
// 否则在在左边
right = mid - 1;
}
}
}
return false;
}
};
边栏推荐
猜你喜欢
随机推荐
十、 网络管理
R language plotly visualization: use the plotly visualization model to predict the true positive rate (True positive) TPR and false positive rate (False positive) FPR curve under different thresholds
tf.where使用
恋爱十不要
主流监控系统工具选型及落地场景参考
The custom table form
PostgreSQL learning summary (11) - PostgreSQL commonly used high-availability cluster solutions
Detailed explanation of calculation commands in shell (expr, (()), $[], let, bc )
【特别提醒】订阅此专栏的用户请先阅读本文再决定是否需要购买此专栏
编程与哲学(2)——输出是为了更好的输入
“蔚来杯“2022牛客暑期多校训练营4
MySQL ODBC驱动简介
三国演义小说
破解wifi密码 暴力破解 保姆式教学
Scala类型转换
Business Intelligence Platform BI Business Intelligence Analysis Platform How to Choose the Right Business Intelligence Platform BI
spark:页面单跳转换率统计(案例)
day_05_pickel 和 json
js函数防抖和函数节流及其使用场景
pnpm的安装与使用









