当前位置:网站首页>LeetCode_二分搜索_中等_153.寻找旋转排序数组中的最小值
LeetCode_二分搜索_中等_153.寻找旋转排序数组中的最小值
2022-07-07 11:27:00 【小城老街】
1.题目
已知一个长度为 n 的数组,预先按照升序排列,经由 1 到 n 次 旋转后,得到输入数组。例如,原数组 nums = [0,1,2,4,5,6,7] 在变化后可能得到:
若旋转 4 次,则可以得到 [4,5,6,7,0,1,2]
若旋转 7 次,则可以得到 [0,1,2,4,5,6,7]
注意,数组 [a[0], a[1], a[2], …, a[n-1]] 旋转一次 的结果为数组 [a[n-1], a[0], a[1], a[2], …, a[n-2]] 。
给你一个元素值互不相同的数组 nums ,它原来是一个升序排列的数组,并按上述情形进行了多次旋转。请你找出并返回数组中的最小元素 。
你必须设计一个时间复杂度为 O(log n) 的算法解决此问题。
示例 1:
输入:nums = [3,4,5,1,2]
输出:1
解释:原数组为 [1,2,3,4,5] ,旋转 3 次得到输入数组。
示例 2:
输入:nums = [4,5,6,7,0,1,2]
输出:0
解释:原数组为 [0,1,2,4,5,6,7] ,旋转 4 次得到输入数组。
示例 3:
输入:nums = [11,13,15,17]
输出:11
解释:原数组为 [11,13,15,17] ,旋转 4 次得到输入数组。
提示:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums 中的所有整数互不相同
nums 原来是一个升序排序的数组,并进行了 1 至 n 次旋转
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-minimum-in-rotated-sorted-array
2.思路
(1)二分搜索
思路参考本题官方题解。
3.代码实现(Java)
//思路1————二分搜索
class Solution {
public static int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
//如果 nums[left] < nums[right],则说明 nums[left...right] 之间的元素是升序的,所以最小元素就是 nums[left]
if (nums[left] < nums[right]) {
return nums[left];
}
int mid = left + (right - left) / 2;
if (nums[mid] < nums[right]) {
right = mid;
} else {
left = mid + 1;
}
}
return nums[right];
}
}
边栏推荐
- Scripy tutorial classic practice [New Concept English]
- Simple and easy-to-use code specification
- MongoDB优化的几点原则
- Common text processing tools
- 存储过程的介绍与基本使用
- Sample chapter of "uncover the secrets of asp.net core 6 framework" [200 pages /5 chapters]
- Vscade editor esp32 header file wavy line does not jump completely solved
- centso7 openssl 报错Verify return code: 20 (unable to get local issuer certificate)
- 如何让electorn打开的新窗口在window任务栏上面
- 抓细抓实抓好安全生产各项工作 全力确保人民群众生命财产安全
猜你喜欢
单片机学习笔记之点亮led 灯
Coscon'22 community convening order is coming! Open the world, invite all communities to embrace open source and open a new world~
How to continue after handling chain interruption / sub chain error removed from scheduling
About how appium closes apps (resolved)
Storage principle inside mongodb
【黑马早报】华为辟谣“军师”陈春花;恒驰5预售价17.9万元;周杰伦新专辑MV 3小时播放量破亿;法华寺回应万元月薪招人...
《开源圆桌派》第十一期“冰与火之歌”——如何平衡开源与安全间的天然矛盾?
ESP32构解工程添加组件
Write it down once Net a new energy system thread surge analysis
Awk of three swordsmen in text processing
随机推荐
error LNK2019: 无法解析的外部符号
JS function 返回多个值
User management summary of mongodb
ClickHouse(03)ClickHouse怎么安装和部署
Cmu15445 (fall 2019) project 2 - hash table details
为租客提供帮助
LED light of single chip microcomputer learning notes
MongoDB优化的几点原则
单片机原理期末复习笔记
解决缓存击穿问题
About how appium closes apps (resolved)
【学习笔记】zkw 线段树
Milkdown 控件图标
共创软硬件协同生态:Graphcore IPU与百度飞桨的“联合提交”亮相MLPerf
JNA learning notes 1: Concepts
clion mingw64中文乱码
MongoDB的用户管理总结
【无标题】
一文读懂数仓中的pg_stat
MongoDB内部的存储原理