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

可以想到,数组中会出现“断层”,直接遍历一次即可。不存在【1,2,3,4,5】旋转成【5,4,3,2,1】的情况。

暴力法(我感觉还行啊,为什么被叫暴力):

class Solution {
    public int minArray(int[] numbers) {
        int n = numbers.length;
        for(int i=0;i<n-1;i++){
            if(numbers[i+1] < numbers[i]){
                return numbers[i+1];
            }
        }
        return numbers[0];
    }
}

二分查找法:(LeetCode上直接粘的):

class Solution {
    public int minArray(int[] numbers) {
        int low = 0;
        int high = numbers.length - 1;
        while (low < high) {
            int pivot = low + (high - low) / 2;
            if (numbers[pivot] < numbers[high]) {
                high = pivot;
            } else if (numbers[pivot] > numbers[high]) {
                low = pivot + 1;
            } else {
                high -= 1;
            }
        }
        return numbers[low];
    }
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/solution/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-by-leetcode-s/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原文地址:https://www.cnblogs.com/yu-jiawei/p/13359076.html