当前位置:网站首页>力扣——旋转数组的最小数字
力扣——旋转数组的最小数字
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】名词缩写
[FPGA] day19- binary to decimal (BCD code)
LeetCode814 Math Question Day 15 Binary Tree Series Value "814 Binary Tree Pruning"
[Likou] 22. Bracket generation
Basic understanding of MongoDB (2)
获取Qt的安装信息:包括安装目录及各种宏地址
Interchangeable Measurement Techniques - Geometric Errors
使用jackson解析json数据详讲
洛谷P2150 寿司晚宴
【深度学习】基于卷积神经网络的天气识别训练
随机推荐
shell监视gpu使用情况
Binary tree related code questions [more complete] C language
洛谷P6586 蒟蒻火锅的盛宴
[FPGA] Design Ideas - I2C Protocol
MYSQLg高级------聚簇索引和非聚簇索引
机器学习中什么是集成学习?
Read the article, high-performance and predictable data center network
UNI-APP_iphone bottom safe area
二叉堆的基础~
How to learn machine learning?machine learning process
【服务器安装mysql】centos7下使用mysql离线安装包安装mysql5.7
Jetson Orin平台4-16路 GMSL2/GSML1相机采集套件推荐
每日一题-滑动窗口
优先级队列
解决多线程调用sql存储过程问题
What are port 80 and port 443?What's the difference?
使用百度EasyDL实现智能垃圾箱
CTO said that the number of rows in a MySQL table should not exceed 2000w, why?
Provincial level of Echart maps, as well as all prefecture-level download and use
【人话版】WEB3将至之“权益的游戏”