当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
随机推荐
Pycharm (1) the basic use of tutorial
Axial Turbine Privacy Policy
TiFlash 存储层概览
Postman download localization of installation and use
新起点丨MeterSphere开源持续测试平台v2.0发布
postman使用方法
The packet capture tool Charles modifies the Response step
UVM之sequence机制
自定义View实现波浪荡漾效果
编程与哲学(2)——输出是为了更好的输入
pnpm: Introduction
“蔚来杯“2022牛客暑期多校训练营4
主流监控系统工具选型及落地场景参考
Technology Cloud Report: To realize the metaverse, NVIDIA starts from building an infrastructure platform
MySQL ODBC驱动简介
C语言基础_共用体
HCIP笔记十六天
tf中tensor的大小输出
在 QT Creator 上配置 opencv 环境的一些认识和注意点
Docker内MySQL主从复制学习,以及遇到的一些问题









