当前位置:网站首页>【Hot100】33. 搜索旋转排序数组
【Hot100】33. 搜索旋转排序数组
2022-07-05 12:56:00 【王六六的IT日常】
33. 搜索旋转排序数组
中等题
但凡是从有序序列中找某个数,第一反应 应该是「二分」。
一个原本有序的数组在某个点上进行了旋转,其实就是将原本一段升序的数组分为了两段。
「二分」的本质是两段性,并非单调性。只要一段满足某个性质,另外一段不满足某个性质,就可以用「二分」。
经过旋转的数组,显然前半段满足 >= nums[0],而后半段不满足 >= nums[0]。我们可以以此作为依据,通过「二分」找到旋转点。
class Solution {
public int search(int[] nums, int target) {
//数组长度
int n = nums.length;
//数组中无元素
if (n == 0) {
return -1;
}
//数组中有一个元素
if (n == 1) {
return nums[0] == target ? 0 : -1;
}
//定义二分查找的左右边界
int l = 0, r = n - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[0] <= nums[mid]) {
//如果target在[l,mid]内一直缩小右边界
if (nums[0] <= target && target < nums[mid]) {
r = mid - 1;
} else {
// target<nums[0] ,target>nums[mid] 不在[l,mid]区间内,往右找
l = mid + 1;
}
} else {
//nums[0] > nums[mid] [5,6,0,1,2,3,4]
if (nums[mid] < target && target <= nums[n - 1]) {
l = mid + 1;
} else {
r = mid - 1;
}
}
}
return -1;
}
}
边栏推荐
- 简单上手的页面请求和解析案例
- [cloud native] use of Nacos taskmanager task management
- 自然语言处理系列(一)入门概述
- 事务的基本特性和隔离级别
- 同事半个月都没搞懂selenium,我半个小时就给他整明白!顺手秀了一波爬淘宝的操作[通俗易懂]
- 解决 UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xa2 in position 107
- STM32 and motor development (from architecture diagram to documentation)
- Taobao product details API | get baby SKU, main map, evaluation and other API interfaces
- PyCharm安装第三方库图解
- Halcon template matching actual code (I)
猜你喜欢

RHCSA9

Pandora IOT development board learning (HAL Library) - Experiment 7 window watchdog experiment (learning notes)

Natural language processing series (I) introduction overview

《2022年中國銀行業RPA供應商實力矩陣分析》研究報告正式啟動

Alipay transfer system background or API interface to avoid pitfalls

【服务器数据恢复】某品牌服务器存储raid5数据恢复案例

Concurrent performance test of SAP Spartacus with JMeter

【云原生】Nacos中的事件发布与订阅--观察者模式

Lb10s-asemi rectifier bridge lb10s

Discussion on error messages and API versions of SAP ui5 getsaplogonlanguage is not a function
随机推荐
Rocky基础知识1
百日完成国产数据库opengausss的开源任务--openGuass极简版3.0.0安装教程
Asemi rectifier bridge hd06 parameters, hd06 pictures, hd06 applications
LeetCode20.有效的括号
精彩速递|腾讯云数据库6月刊
MySQL splits strings for conditional queries
MSTP and eth trunk
There is no monitoring and no operation and maintenance. The following is the commonly used script monitoring in monitoring
你的下一台电脑何必是电脑,探索不一样的远程操作
Alipay transfer system background or API interface to avoid pitfalls
峰会回顾|保旺达-合规和安全双驱动的数据安全整体防护体系
RHCSA1
Yyds dry inventory JS intercept file suffix
Introduction to sap ui5 flexiblecolumnlayout control
Cf:a. the third three number problem
MySQL 巨坑:update 更新慎用影响行数做判断!!!
量价虽降,商业银行结构性存款为何受上市公司所偏爱?
About the single step debugging of whether SAP ui5 floating footer is displayed or not and the benefits of using SAP ui5
使用 jMeter 对 SAP Spartacus 进行并发性能测试
Leetcode20. Valid parentheses