当前位置:网站首页>【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;
}
}
边栏推荐
- Why is your next computer a computer? Explore different remote operations
- 你的下一台电脑何必是电脑,探索不一样的远程操作
- 跨平台(32bit和64bit)的 printf 格式符 %lld 输出64位的解决方式
- 155. 最小栈
- Reverse Polish notation
- Asemi rectifier bridge hd06 parameters, hd06 pictures, hd06 applications
- 单独编译内核模块
- Insmod prompt invalid module format
- A small talk caused by the increase of sweeping
- Hiengine: comparable to the local cloud native memory database engine
猜你喜欢
Get to know linkerd project for the first time
自然语言处理系列(一)入门概述
爱可生SQLe审核工具顺利完成信通院‘SQL质量管理平台分级能力’评测
It's too convenient. You can complete the code release and approval by nailing it!
Principle and configuration of RSTP protocol
Hundred days to complete the open source task of the domestic database opengauss -- openguass minimalist version 3.0.0 installation tutorial
Introduction aux contrôles de la page dynamique SAP ui5
RHCSA3
使用 jMeter 对 SAP Spartacus 进行并发性能测试
Shi Zhenzhen's 2021 summary and 2022 outlook | colorful eggs at the end of the article
随机推荐
Rocky基础命令3
单独编译内核模块
RHCAS6
A deep long article on the simplification and acceleration of join operation
Asemi rectifier bridge hd06 parameters, hd06 pictures, hd06 applications
峰会回顾|保旺达-合规和安全双驱动的数据安全整体防护体系
How to protect user privacy without password authentication?
逆波兰表达式
Principle and configuration of RSTP protocol
PyCharm安装第三方库图解
Laravel document reading notes -mews/captcha use (verification code function)
Concurrent performance test of SAP Spartacus with JMeter
SAP UI5 FlexibleColumnLayout 控件介绍
关于 Notion-Like 工具的反思和畅想
碎片化知识管理工具Memos
AVC1与H264的区别
Setting up sqli lab environment
What is the difference between Bi software in the domestic market
APICloud Studio3 WiFi真机同步和WiFi真机预览使用说明
Talk about my drawing skills in my writing career