当前位置:网站首页>81.搜索旋转排序数组II(数组旋转后二分查找)
81.搜索旋转排序数组II(数组旋转后二分查找)
2022-07-30 05:38:00 【Linke66】

记录一下:
if(nums[left]==nums[mid]){
//无法判断哪个区间是升序的
++left;
}
假如是上面这种情况,反正是寻找有无target,两个元素相等,直接让left往右移动一个,直到能够判断左边还是右边是升序!
class Solution {
public:
bool search(vector<int>& nums, int target) {
int left=0,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;
}else if(nums[mid]<=nums[right]){
//右区间是升序的
if(target>nums[mid]&&target<=nums[right]){
left=mid+1;
}else{
right=mid-1;
}
}else
{
//左区间是升序的
if(target<nums[mid]&&target>=nums[left]){
right=mid-1;
}else{
left=mid+1;
}
}
}
return false;
}
};

特别注意相等的时候,
不能随意忽略左界或右界,因为无法确定左界升序还是右界升序,因此只能忽略一个元素,即right=right-1;
class Solution {
public:
int findMin(vector<int>& nums) {
int left=0,right=nums.size()-1;
while(left<right)
{
int mid=left+(right-left)/2;
if(nums[mid]<nums[right]){
//更新右界,最小元素不可能在mid右边,mid可能是最小的元素
right=mid;
}else if(nums[mid]>nums[right]){
//更新左界,最小元素一定在mid右边
left=mid+1;
}else{
//不能随意忽略任一部分,但是可以忽略右端点
//因为是跟右界比的,既然相等就忽略右端点
right-=1;
}
}
return nums[left];
}
};
边栏推荐
- asyncawait和promise的区别
- Teach you to completely uninstall MySQL
- 质数(清华大学机试题)(DAY 86)
- cnpm安装步骤
- The use of Conluce, an online document management system
- Countdown (Source: Google Kickstart2020 Round C Problem A) (DAY 88)
- “tensorflow.keras.preprocessing“ has no attribute “image_dataset_from_directory“
- 【Koltin Flow(二)】Flow操作符之末端操作符
- MySql模糊查询大全
- [Mysql] DATEDIFF function
猜你喜欢

Teach you how to design a CSDN system

MySQL Soul 16 Questions, how many questions can you last?

MySQL模糊查询性能优化

mysql 中 in 的用法

MySQL 用户授权
![[Image detection] Research on cumulative weighted edge detection method based on grayscale image with matlab code](/img/c1/f962f1c1d9f75732157d49a5d1d0d6.png)
[Image detection] Research on cumulative weighted edge detection method based on grayscale image with matlab code

号称年薪30万占比最多的专业,你知道是啥嘛?

Solve phpstudy unable to start MySQL service

navicat连接MySQL报错:1045 - Access denied for user ‘root‘@‘localhost‘ (using password YES)

CISP-PTE Zhenti Demonstration
随机推荐
HCIP-第九天-BGP(边界网关协议)
[Mysql] CONVERT函数
PyCharm usage tutorial (more detailed, picture + text)
MySql的初识感悟,以及sql语句中的DDL和DML和DQL的基本语法
Solve the problem that the local nacos is not configured but the localhost8848 connection exception always occurs
G Bus Count (Google Kickstart2014 Round D Problem B) (DAY 89)
Frobenius norm(Frobenius 范数)
2022 SQL big factory high-frequency practical interview questions (detailed analysis)
应用实践 | Apache Doris 在百度智能云计费账单系统的应用实践
机器学习—梯度下降Gradient Descent Optimization—c语言实现
成绩排序(华中科技大学考研机试题)(DAY 87)
【Koltin Flow(一)】五种创建flow的方式
nacos-2.0.3启动报错出现no datasource set的坑
破纪录者(Google Kickstart2020 Round D Problem A)
4461. 范围分区(Google Kickstart2022 Round C Problem B)
Introduction to Oracle Patch System and Opatch Tool
【Koltin Flow(二)】Flow操作符之末端操作符
瑞吉外卖项目:新增菜品与菜品分页查询
MySQL 用户授权
手把手教你彻底卸载MySQL