当前位置:网站首页>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;
}
};
边栏推荐
- 大厂外包,值得拥有吗?
- USACO美国信息学奥赛竞赛12月份开赛,中国学生备赛指南
- 天地图给多边形加标注
- EPSANet: An Efficient Pyramid Split Attention Block on Convolutional Neural Network
- UVM信息服务机制
- day——05 迭代器,生成器
- How Engineers Treat Open Source --- A veteran engineer's heartfelt words
- 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
- 【开源项目】X-TRACK源码分析
- JSP页面中page指令contentPage/pageEncoding具有什么功能呢?
猜你喜欢
随机推荐
mysql 中 in 的用法
C语言基础_结构体
day_05_pickel 和 json
练习40,小蓝的旅行【最短路】
pycharm的基本使用教程(1)
etcd implements large-scale service governance application combat
What is the function of page directive contentPage/pageEncoding in JSP page?
shell脚本
Wang Xuegang - compiled shipment line file
(Note) AXIS ACASIS DT-3608 Dual-bay Hard Disk Array Box RAID Setting
【特别提醒】订阅此专栏的用户请先阅读本文再决定是否需要购买此专栏
postman下载安装汉化及使用
Qt读取文件中内容(通过判断GBK UTF-8格式进行读取显示)
openpyxl 单元格合并
RestTemlate源码分析及工具类设计
Technology Cloud Report: To realize the metaverse, NVIDIA starts from building an infrastructure platform
uvm-phase机制
Pycharm (1) the basic use of tutorial
谈谈对Volatile的理解
UVM信息服务机制