当前位置:网站首页>LeetCode刷题日记:153、寻找旋转排序数组中的最小值
LeetCode刷题日记:153、寻找旋转排序数组中的最小值
2022-08-02 01:44:00 【淡墨@~无痕】
已知一个长度为 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 次旋转
思路:与搜索旋转排序数组差别不大
题解:
class Solution {
public int findMin(int[] nums) {
int res = Integer.MAX_VALUE;
int start = 0, end = nums.length-1;
if(nums.length == 0){
return -1;
}
while (start <= end) {
int mid = (start + end)/2;
// 查找最小值
res = Math.min(res, nums[start]);
res = Math.min(res, nums[end]);
res = Math.min(res, nums[mid]);
if(nums[start] <= nums[mid]){
if(nums[start] <= res && res < nums[mid] ){
end = mid-1;
}else{
start = mid + 1;
}
}else{
if(nums[mid] < res && res <= nums[nums.length-1]){
start = mid + 1;
}else{
end = mid - 1;
}
}
}
return res;
}
}
边栏推荐
- C语言实验九 函数(一)
- The ultra-large-scale industrial practical semantic segmentation dataset PSSL and pre-training model are open source!
- 关于MySQL的数据插入(高级用法)
- C语言实验六 一维数组程序设计
- HSDC is related to Independent Spanning Tree
- C语言实验十 函数(二)
- 华为5年女测试工程师离职:多么痛的领悟...
- ofstream,ifstream,fstream读写文件
- 【Brush the title】Family robbery
- Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
猜你喜欢

Redis cluster mode

喜报 | AR 开启纺织产业新模式,ALVA Systems 再获殊荣!

hash table

Use flex-wrap to wrap lines in flex layout

typescript38-class的构造函数实例方法继承(implement)
软件测试功能测试全套常见面试题【开放性思维题】面试总结4-3

Navicat data shows incomplete resolution

信息化和数字化的本质区别是什么?

Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion

华为5年女测试工程师离职:多么痛的领悟...
随机推荐
fastjson详解
Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
待读书单列表
Rust P2P Network Application Combat-1 P2P Network Core Concepts and Ping Program
Reflex WMS中阶系列7:已经完成拣货尚未Load的HD如果要取消拣货,该如何处理?
三本毕业的我被腾讯拒绝了十四次,最终成功入职阿里
60种特征工程操作:使用自定义聚合函数【收藏】
大话西游创建角色失败解决
Flink_CDC construction and simple use
Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided
6-25漏洞利用-irc后门利用
乱七八糟的网站
Redis 订阅与 Redis Stream
电商库存系统的防超卖和高并发扣减方案
typescript29-枚举类型的特点和原理
typescript32-ts中的typeof
成都openGauss用户组招募啦!
字节给我狠狠上了一课:危机来的时候你连准备时间都没有...
Named parameter implementation of JDBC PreparedStatement
Flex布局详解