当前位置:网站首页>【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;
}
}
边栏推荐
- SAP SEGW 事物码里的 ABAP Editor
- RHCSA1
- How can non-technical departments participate in Devops?
- Association modeling method in SAP segw transaction code
- Write macro with word
- 阿里云SLB负载均衡产品基本概念与购买流程
- 峰会回顾|保旺达-合规和安全双驱动的数据安全整体防护体系
- 《2022年中国银行业RPA供应商实力矩阵分析》研究报告正式启动
- 《2022年中國銀行業RPA供應商實力矩陣分析》研究報告正式啟動
- ##无监控,不运维,以下是监控里常用的脚本监控
猜你喜欢

Hiengine: comparable to the local cloud native memory database engine

RHCSA9

解决 UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xa2 in position 107

MySQL giant pit: update updates should be judged with caution by affecting the number of rows!!!

你的下一台电脑何必是电脑,探索不一样的远程操作

Taobao short video, why the worse the effect

Natural language processing series (I) introduction overview

阿里云SLB负载均衡产品基本概念与购买流程

UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xe6 in position 76131: invalid continuation byt

蜀天梦图×微言科技丨达梦图数据库朋友圈+1
随机推荐
初识Linkerd项目
Overflow toolbar control in SAP ui5 view
leetcode:221. 最大正方形【dp状态转移的精髓】
LeetCode20.有效的括号
峰会回顾|保旺达-合规和安全双驱动的数据安全整体防护体系
Introduction aux contrôles de la page dynamique SAP ui5
聊聊异步编程的 7 种实现方式
国内市场上的BI软件,到底有啥区别
简单上手的页面请求和解析案例
RHCSA8
RHCSA1
MySQL splits strings for conditional queries
APICloud Studio3 API管理与调试使用教程
ASEMI整流桥HD06参数,HD06图片,HD06应用
国际自动机工程师学会(SAE International)战略投资几何伙伴
HiEngine:可媲美本地的云原生内存数据库引擎
Four common problems of e-commerce sellers' refund and cash return, with solutions
ABAP editor in SAP segw transaction code
潘多拉 IOT 开发板学习(HAL 库)—— 实验7 窗口看门狗实验(学习笔记)
SAP SEGW 事物码里的导航属性(Navigation Property) 和 EntitySet 使用方法