【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA)

【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 原来是一个升序排序的数组,但在预先未知的某个点上进行了旋转

解题方法

  1. 既然是排序过的数组,只是某个地方翻转了,那就可以用二分法,找出逆转的位置即可
  2. 如果 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 每日一题更新
【LeetCode】153. Find Minimum in Rotated Sorted Array 寻找旋转排序数组中的最小值(Medium)(JAVA)
上一篇:20145334 《Java程序设计》第10周学习总结


下一篇:linux之SQL语句简明教程---SUBSTRING