当前位置:网站首页>LeetCode Review Diary: 153. Find the Minimum Value in a Rotated Sort Array
LeetCode Review Diary: 153. Find the Minimum Value in a Rotated Sort Array
2022-08-02 01:55:00 【light [email protected]】
已知一个长度为 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;
}
}
版权声明
本文为[light [email protected]~no trace]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020144011216.html
边栏推荐
猜你喜欢

力扣 1161. 最大层内元素和

制造企业数字化转型现状分析

LeetCode刷题日记:74. 搜索二维矩阵

Constructor instance method inheritance of typescript38-class (implement)

3 Month Tester Readme: 4 Important Skills That Impacted My Career

安全(2)

『网易实习』周记(二)

『网易实习』周记(一)

oracle查询扫描全表和走索引

Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation
随机推荐
Constructor of typescript35-class
Reflex WMS中阶系列7:已经完成拣货尚未Load的HD如果要取消拣货,该如何处理?
6-25 Vulnerability Exploitation - irc Backdoor Exploitation
【轮式里程计】
YGG 公会发展计划第 1 季总结
Newton's theorem and related corollaries
ALCCIKERS Shane 20191114
【刷题篇】打家劫舍
创新项目实战之智能跟随机器人原理与代码实现
一本适合职场新人的好书
Constructor instance method of typescript36-class
Anti-oversold and high concurrent deduction scheme for e-commerce inventory system
typescript36-class的构造函数实例方法
Navicat data shows incomplete resolution
"NetEase Internship" Weekly Diary (2)
typescript29-枚举类型的特点和原理
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
传统企业数字化转型需要经过几个阶段?
Moonbeam与Project Galaxy集成,为社区带来全新的用户体验
字节给我狠狠上了一课:危机来的时候你连准备时间都没有...