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

【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:

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:

题目大意

假设按照升序排序的数组在预先未知的某个点上进行了旋转。例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] 。

请找出其中最小的元素。

提示:

解题方法

  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 每日一题更新

标签:153,JAVA,nums,rotated,Rotated,times,数组,array,was
来源: https://blog.csdn.net/qq_16927853/article/details/110091704