154. Find Minimum in Rotated Sorted Array II - Hard

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).

Find the minimum element.

The array may contain duplicates.

Example 1:

Input: [1,3,5]
Output: 1

Example 2:

Input: [2,2,2,0,1]
Output: 0

Note:

 

153. find minimum in rotated sorted array的follow up  https://www.cnblogs.com/fatttcat/p/10061983.html

数组里可以有重复元素,还是一样用binary search

如果array[mid] < array[right]说明最小值在mid的右侧,应该在mid的下一位开始找起;

如果array[mid] > array[right]说明右边的数组是递增的,最小值在mid或mid的左侧,right = mid;

如果array[mid] = array[right],减小数组长度,right--

最后判断一下左右边界,谁小返回谁

time: O(logn)  -- worst case O(n) if all elements are same, space: O(1)

class Solution {
    public int findMin(int[] nums) {
        if(nums == null || nums.length == 0) return -1;
        int l = 0, r = nums.length - 1;
        while(l + 1 < r) {
            int m = l + (r - l) / 2;
            if(nums[m] > nums[r])
                l = m + 1;
            else if(nums[m] < nums[r])
                r = m;
            else
                r--;
        }
        return nums[l] < nums[r] ? nums[l] : nums[r];
    }
}

 

posted @ 2018-12-19 12:40  fatttcat  阅读(89)  评论(0编辑  收藏  举报