返回轨道
算法 · 2026-05-14 · 16 阅读

P127 旋转有序数组的最小值

算法 16 阅读

信号摘要

难度:Medium · 时长:05:48 · leetcode 153 · lintcode 159

P127 旋转有序数组的最小值

未对外公开播放权限
点击查看说明

描述

这个题目说的是,给你一个不为空的旋转有序数组,数组中不包含重复数字,你要找到这个数组中的最小值并返回它。旋转有序数组是由一个原来有序的数组通过左旋或右旋部分数字到另一端形成的。注意,这里我们讨论的有序默认都指递增排序。

比如说,原来的有序数组是 0, 1, 2, 4, 8,把 0, 1 旋转到数组右边,得到的数组 a 是:

2, 4, 8, 0, 1

在这个数组中,最小值是 0,因此你要返回 0。

代码

public class AlgoCasts {

  // Time: O(log(n)), Space: O(1)
  public int findMin(int[] nums) {
    int low = 0, high = nums.length - 1;
    while (low < high) {
      int mid = low + (high - low) / 2;
      if (nums[mid] > nums[high]) low = mid + 1;
      else high = mid;
    }
    return nums[low];
  }

  // Time: O(log(n)), Space: O(1)
  public int findMinEarlyReturn(int[] nums) {
    int low = 0, high = nums.length - 1;
    while (low < high) {
      if (nums[low] < nums[high]) return nums[low];
      int mid = low + (high - low) / 2;
      if (nums[mid] > nums[high]) low = mid + 1;
      else high = mid;
    }
    return nums[low];
  }

}

📡 通讯频道