当前位置:网站首页>【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;
}
}
边栏推荐
- Put functions in modules
- SAP UI5 ObjectPageLayout 控件使用方法分享
- Developers, is cloud native database the future?
- Reverse Polish notation
- How can non-technical departments participate in Devops?
- mysql econnreset_Nodejs 套接字报错处理 Error: read ECONNRESET
- RHCSA8
- Halcon 模板匹配实战代码(一)
- 解决 UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xa2 in position 107
- ABAP editor in SAP segw transaction code
猜你喜欢
Shi Zhenzhen's 2021 summary and 2022 outlook | colorful eggs at the end of the article
自然语言处理系列(一)入门概述
leetcode:221. 最大正方形【dp状态转移的精髓】
Pycharm installation third party library diagram
Hiengine: comparable to the local cloud native memory database engine
Actual combat simulation │ JWT login authentication
碎片化知识管理工具Memos
Reverse Polish notation
Binder通信过程及ServiceManager创建过程
Principle and performance analysis of lepton lossless compression
随机推荐
Setting up sqli lab environment
Reverse Polish notation
946. Verify stack sequence
APICloud Studio3 WiFi真机同步和WiFi真机预览使用说明
APICloud Studio3 API管理与调试使用教程
A deep long article on the simplification and acceleration of join operation
开发者,云原生数据库是未来吗?
碎片化知识管理工具Memos
解决uni-app配置页面、tabBar无效问题
RHCSA3
Shi Zhenzhen's 2021 summary and 2022 outlook | colorful eggs at the end of the article
Introduction to sap ui5 dynamicpage control
leetcode:221. Maximum square [essence of DP state transition]
Alibaba cloud SLB load balancing product basic concept and purchase process
Put functions in modules
Principle and configuration of RSTP protocol
使用 jMeter 对 SAP Spartacus 进行并发性能测试
Introduction to sap ui5 flexiblecolumnlayout control
Install rhel8.2 virtual machine
Developers, is cloud native database the future?