Loading

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

https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/

最坏的时间复杂度是O(n)的
image

思路:
先把后面的末尾与前面的开始的那段去掉(因为可能有重复的数字)
处理数组完全单调的特殊情况:去掉重复的之后nums[n] > nums[0]
然后使用二分

class Solution {
    public int findMin(int[] nums) {
        int n = nums.length - 1;
        if(n < 0) return -1;
        while(n > 0 && nums[0] == nums[n]) n--;
        if(nums[n] > nums[0]) return nums[0];
        int l = 0, r = n;
        while(l < r){
            int mid = l + r >> 1;
            if(nums[mid] < nums[0]) r = mid;
            else l = mid + 1;
        }
        return nums[r];
    }
}
posted @ 2021-12-28 23:08  Zhbeii  阅读(22)  评论(0)    收藏  举报