当前位置:网站首页>LeetCode_二分搜索_中等_153.寻找旋转排序数组中的最小值
LeetCode_二分搜索_中等_153.寻找旋转排序数组中的最小值
2022-07-07 11:27:00 【小城老街】
1.题目
已知一个长度为 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 次旋转
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-minimum-in-rotated-sorted-array
2.思路
(1)二分搜索
思路参考本题官方题解。
3.代码实现(Java)
//思路1————二分搜索
class Solution {
public static int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
//如果 nums[left] < nums[right],则说明 nums[left...right] 之间的元素是升序的,所以最小元素就是 nums[left]
if (nums[left] < nums[right]) {
return nums[left];
}
int mid = left + (right - left) / 2;
if (nums[mid] < nums[right]) {
right = mid;
} else {
left = mid + 1;
}
}
return nums[right];
}
}
边栏推荐
猜你喜欢
随机推荐
学习突围2 - 关于高效学习的方法
[etc.] what are the security objectives and implementation methods that cloud computing security expansion requires to focus on?
Mongodb command summary
一文读懂数仓中的pg_stat
Differences between MySQL storage engine MyISAM and InnoDB
【学习笔记】线段树选做
[Presto profile series] timeline use
[learning notes] agc010
Mongodb slice summary
ESP32构解工程添加组件
Japanese government and enterprise employees got drunk and lost 460000 information USB flash drives. They publicly apologized and disclosed password rules
About the problem of APP flash back after appium starts the app - (solved)
Mongodb meets spark (for integration)
信号强度(RSSI)知识整理
Read PG in data warehouse in one article_ stat
API query interface for free mobile phone number ownership
Mongodb replication (replica set) summary
MySQL入门尝鲜
Sed of three swordsmen in text processing
MongoDB优化的几点原则