当前位置:网站首页>力扣——旋转数组的最小数字
力扣——旋转数组的最小数字
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】SDRAM

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

Differences and connections between distributed and clustered

LeetCode刷题第11天字符串系列之《 58最后一个单词长度》

【FPGA】day19-二进制转换为十进制(BCD码)

干货:服务器网卡组技术原理与实践

机器学习可以应用在哪些场景?机器学习有什么用?

Day20 FPGA 】 【 - block the I2C read and write EEPROM
![Binary tree related code questions [more complete] C language](/img/85/a109eed69cd54be3c8290e8dd67b7c.png)
Binary tree related code questions [more complete] C language

一文读懂 高性能可预期数据中心网络
随机推荐
leetCode刷题14天二叉树系列之《 110 平衡二叉树判断》
洛谷P4061 大吉大利,晚上吃鸡
Audio codec, using FAAC to implement AAC encoding
洛谷P7441 Erinnerung
Which one to choose for mobile map development?
Description of ESB product development steps under cloud platform
优先级队列
es-head插件插入查询以及条件查询(五)
Echart地图的省级,以及所有地市级下载与使用
Watch to monitor
C# 一周入门高级编程之《C#-LINQ》Day Four
The custom of the C language types -- -- -- -- -- - structure
洛谷P2370 yyy2015c01 的 U 盘
LeetCode814算题第15天二叉树系列值《814 二叉树剪枝》
移动端地图开发选择哪家?
Is there any way for kingbaseES to not read the system view under sys_catalog by default?
这些云自动化测试工具值得拥有
洛谷P2245 星际导航
What is third-party payment?
LeetCode刷题第12天二叉树系列之《104 二叉树的最大深度》