当前位置:网站首页>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
边栏推荐
- Constructor of typescript35-class
- For effective automated testing, these software testing tools must be collected!!!
- Navicat data shows incomplete resolution
- 【Brush the title】Family robbery
- HSDC is related to Independent Spanning Tree
- Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
- typescript36-class的构造函数实例方法
- Understand the big model in seconds | 3 steps to get AI to write a summary
- Redis 持久化 - RDB 与 AOF
- 手写一个博客平台~第三天
猜你喜欢
随机推荐
5年自动化测试经验的一些感悟:做UI自动化一定要跨过这10个坑
Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
Effects of Scraping and Aggregation
Fly propeller power space future PIE - Engine Engine build earth science
Navicat data shows incomplete resolution
The ultra-large-scale industrial practical semantic segmentation dataset PSSL and pre-training model are open source!
垃圾回收器CMS和G1
力扣 1161. 最大层内元素和
秒懂大模型 | 3步搞定AI写摘要
3 Month Tester Readme: 4 Important Skills That Impacted My Career
牛顿定理和相关推论
pcie inbound和outbound关系
华为5年女测试工程师离职:多么痛的领悟...
《自然语言处理实战入门》 基于知识图谱的问答机器人
R语言使用cph函数和rcs函数构建限制性立方样条cox回归模型、使用anova函数进行方差分析通过p值确认指定连续变量和风险值HR之间是否存在非线性关系
大话西游创建角色失败解决
3. Bean scope and life cycle
Byte taught me a hard lesson: When a crisis comes, you don't even have time to prepare...
TKU记一次单点QPS优化(顺祝ITEYE终于回来了)
"NetEase Internship" Weekly Diary (2)









