剑指—旋转数组的最小数字

117 阅读1分钟

剑指 Offer 11. 旋转数组的最小数字

  • 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
  • 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
  • 例如,数组 [3,4,5,1,2][1,2,3,4,5] 的一个旋转,该数组的最小值为1。
示例 1:

输入:[3,4,5,1,2]
输出:1

示例 2:

输入:[2,2,2,0,1]
输出:0

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/xu…

用java自带函数做

class Solution {
    public int minArray(int[] numbers) {
        if(numbers == null) return null;

        Arrays.sort(numbers);
        return numbers[0];
    }
}

O(1)遍历做

class Solution {
    public int minArray(int[] numbers) {
       if(numbers.length == 1)return numbers[0];

       int i = 1;
       while (i < numbers.length) {
           if (numbers[i-1] > numbers[i]) {
               //因为这个数组是递增的,只要找出终止递增的那个点  那就一定是最小值
               return numbers[i];      
           } else {
               i++;
           }
       }
       return numbers[0];
    }
}
  • 左右都记录一个lownumheightnum
    • 分别根据数组的特性去两端判断

双向查找

class Solution {
    public int minArray(int[] numbers) {
        // 3 4 5 1 2
        //   l   h h
        int low = 0,height = numbers.length - 1;

        int lownum = numbers[0];   //最小数记录
        int heightnum = numbers[height];   // 伪最大数记录

        while (height > low) {
            low++;        // 左指针前进
            height--;     // 右指针前进
            if (lownum > numbers[low]) {    
                // 如果出现比最小数小的数,直接返回
                return numbers[low];
            }
            if (heightnum < numbers[height]) {
                // 如果出现比伪最大数还有大的数
                return heightnum;
            }
            lownum = numbers[low];
            heightnum = numbers[height];
        }

        return numbers[0];
    }
}