【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2127字,纯文字阅读大概需要4分钟。
内容图文
![【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA)](/upload/InfoBanner/zyjiaocheng/621/6911cf60c42f4355bc2df0ecc93cbff8.jpg)
【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA)
题目地址: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
题目描述:
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
- [4,5,6,7,0,1,2] if it was rotated 4 times.
- [0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], …, a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], …, a[n-2]].
Given the sorted rotated array nums, return the minimum element of this array.
Example 1:
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
Example 2:
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
Example 3:
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times.
Constraints:
- n == nums.length
- 1 <= n <= 5000
- -5000 <= nums[i] <= 5000
- All the integers of nums are unique.
- nums is sorted and rotated between 1 and n times.
题目大意
假设按照升序排序的数组在预先未知的某个点上进行了旋转。例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] 。
请找出其中最小的元素。
提示:
- 1 <= nums.length <= 5000
- -5000 <= nums[i] <= 5000
- nums 中的所有整数都是 唯一 的
- nums 原来是一个升序排序的数组,但在预先未知的某个点上进行了旋转
解题方法
- 既然是排序过的数组,只是某个地方翻转了,那就可以用二分法,找出逆转的位置即可
- 如果 nums[start] <= nums[end],直接返回 nums[start] 即可;如果 nums[start] <= nums[mid],表明 [start, mid] 是升序的,结果在 [mid + 1, end];如果 nums[start] > nums[mid],表明结果在 [start + 1, mid]
class Solution {
public int findMin(int[] nums) {
int start = 0;
int end = nums.length - 1;
while (start <= end) {
if (nums[start] <= nums[end]) return nums[start];
int mid = start + (end - start) / 2;
if (nums[start] <= nums[mid]) {
start = mid + 1;
} else {
end = mid;
start++;
}
}
return 0;
}
}
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:37.9 MB,击败了80.89% 的Java用户
![【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA) - 文章图片](/upload/getfiles/0001/2021/5/1/20210501122649068.jpg)
内容总结
以上是互联网集市为您收集整理的【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA)全部内容,希望文章能够帮你解决【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。