当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
四字节的float比八字结的long范围大???
RetinaFace: Single-stage Dense Face Localisation in the Wild
unity pdg 设置隐藏不需要的节点以及实现自动勾选自动加载项
OneNote Tutorial, How to Create More Spaces in OneNote?
postman下载安装汉化及使用
How Engineers Treat Open Source --- A veteran engineer's heartfelt words
spark:热门品类中每个品类活跃的SessionID统计TOP10(案例)
UVM事务级建模
Redis分布式锁入门
动态规划每日一练(3)
随机推荐
在 QT Creator 上配置 opencv 环境的一些认识和注意点
PyCharm使用教程(详细版 - 图文结合)
In a recent build figure SLAM, and locate the progress
类和对象【下】
USACO美国信息学奥赛竞赛12月份开赛,中国学生备赛指南
Axial Turbine Privacy Policy
R language plotly visualization: plotly visualizes the scatter plot of the actual value of the regression model and the predicted value of the regression, analyzes the prediction performance of the re
Qt读取文件中内容(通过判断GBK UTF-8格式进行读取显示)
LeetCode_2357_使数组种所有元素都等于零
C语言_条件编译
AttributeError: module ‘clr‘ has no attribute ‘AddReference‘
Redisson实现分布式锁
每天花2小时恶补腾讯T8纯手打688页SSM框架和Redis,成功上岸美团
十、 网络管理
SVN下载上传文件
Business Intelligence Platform BI Business Intelligence Analysis Platform How to Choose the Right Business Intelligence Platform BI
next permutation
spark:商品热门品类TOP10统计(案例)
了解下C# 多线程
sql concat(),如何才能拼接表的名字