当前位置:网站首页>力扣——旋转数组的最小数字
力扣——旋转数组的最小数字
2022-08-11 04:13:00 【cbys-1357】
题目:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
给你一个可能存在 重复 元素值的数组 numbers ,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一次旋转,该数组的最小值为 1。
注意,数组 [a[0], a[1], a[2], ..., a[n-1]] 旋转一次 的结果为数组 [a[n-1], a[0], a[1], a[2], ..., a[n-2]] 。
例1:
输入:numbers = [3,4,5,1,2] 输出:1
例2:
输入:numbers = [2,2,2,0,1] 输出:0
二分查找
题目中给出的是半有序数组,虽然传统二分告诉我们二分只能用在有序数组中,但事实上,只要是可以减治的问题,仍然可以使用二分思想。
思路:数组中最特殊的位置是左边位置 left 和右边位置 right,将它们与中间位置 mid 的值进行比较,进而判断最小数字出现在哪里。
用左边位置 left 和中间位置 mid 的值进行比较是否可以?
举例:[3, 4, 5, 1, 2] 与 [1, 2, 3, 4, 5] ,此时,中间位置的值都比左边大,但最小值一个在后面,一个在前面,因此这种做法不能有效地减治。
用右边位置 right 和中间位置 mid 的值进行比较是否可以?
举例:[1, 2, 3, 4, 5]、[3, 4, 5, 1, 2]、[2, 3, 4, 5 ,1],用右边位置和中间位置的元素比较,可以进一步缩小搜索的范围。
补充说明:遇到 nums[mid] == nums[right] 的时候,不能草率地下定结论最小数字在哪一边,但是可以确定的是,把 right 舍弃掉,并不影响结果。
代码实现:
class Solution {
public int minArray(int[] numbers) {
int low=0;
int height=numbers.length-1;
while(low<height){
int mid=(low+height)/2;
if(numbers[mid]>numbers[height]){
low=mid+1;
}else if(numbers[mid]==numbers[height]){
height--;
}else{
height=mid;
}
}
return numbers[low];
}
}本题是利用二分查找的思想,不断缩小范围,最后找到那个最小值 。
活动地址:CSDN21天学习挑战赛
边栏推荐
- 【FPGA】设计思路——I2C协议
- 【FPGA】day20-I2C读写EEPROM
- 【FPGA】day22-SPI protocol loopback
- CTO said that the number of rows in a MySQL table should not exceed 2000w, why?
- The development of the massage chair control panel makes the massage chair simple and intelligent
- 80端口和443端口是什么?有什么区别?
- es-head插件插入查询以及条件查询(五)
- .NET Custom Middleware
- 【FPGA】day21- moving average filter
- 移动端地图开发选择哪家?
猜你喜欢

北湖区燕泉街道开展“戴头盔·保安全”送头盔活动

【人话版】WEB3将至之“权益的游戏”

The last update time of the tables queried by the two nodes of the rac standby database is inconsistent

什么是机器强化学习?原理是什么?

The custom of the C language types -- -- -- -- -- - structure
![[Likou] 22. Bracket generation](/img/f6/435fe9e0b4c1545514d1bf195ffd44.png)
[Likou] 22. Bracket generation

【FPGA】day22-SPI协议回环

WPF DataGrid 使用数据模板(2)

【FPGA】abbreviation

洛谷P2150 寿司晚宴
随机推荐
机器学习怎么学?机器学习流程
1815. 得到新鲜甜甜圈的最多组数 状态压缩
"3 Longest Substring Without Repeating Characters" on the 17th day of LeetCode brushing
Description of ESB product development steps under cloud platform
Map中的getOrDefualt方法
LeetCode刷题第10天字符串系列之《125回文串验证》
利用Navicat Premium导出数据库表结构信息至Excel
LeetCode刷题第17天之《3 无重复字符的最长子串》
Element's BFC attribute
Power Cabinet Data Monitoring RTU
CTO said that the number of rows in a MySQL table should not exceed 2000w, why?
移动端地图开发选择哪家?
【FPGA】day22-SPI协议回环
Basic understanding of MongoDB (2)
Graphical LeetCode - 640. Solving Equations (Difficulty: Moderate)
如何进行AI业务诊断,快速识别降本提效增长点?
我的 archinstall 使用手册
拼多多店铺营业执照相关问题
每日一题-滑动窗口
干货:服务器网卡组技术原理与实践