[LeetCode 154] Find Minimum in Rotated Sorted Array (Hard)

Solution

  1. 与#153的区别就是,需要处理重复的情况,即同样当A[mid] = A[end]时,无法判断min究竟在左边还是右边。
3 1 2 3 3 3 3 
3 3 3 3 1 2 3

但可以肯定的是可以排除A[end]:因为即使min = A[end],由于A[end] = A[mid],排除A[end]并没有让min丢失。所以增加的条件是:

A[mid] = A[end]:搜索A[start : end-1], 即end--

class Solution {
//     public int findMin(int[] nums) {
//         int left = 0;
//         int right = nums.length - 1;
        
//         return findMin (nums, left, right);
//     }
    
//     public int findMin (int[] nums, int left, int right) {
//         if (nums[left] < nums[right]) {
//             return nums[left];
//         }
        
//         if (left + 1 >= right) {
//             return Math.min (nums[left], nums[right]);
//         }
        
        
//         int middle = left + (right - left) / 2;
//         int min1 = findMin (nums, left, middle);
//         int min2 = findMin (nums, middle + 1, right);

//         return Math.min (min1, min2);
//     }
    
    public int findMin(int[] nums) {
        if (nums == null || nums.length == 0)
            return Integer.MIN_VALUE;
        
        int start = 0;
        int end = nums.length - 1;
        
        while (start + 1 < end) {
            int middle = start + (end - start) / 2;
            
            if (nums [middle] < nums [end]) {
                end = middle;
            } else if (nums [middle] > nums [end]) {
                start = middle;
            } else {
                end --;
            }
        }
    
        return Math.min (nums [start], nums [end]);
    }
}

你可能感兴趣的:([LeetCode 154] Find Minimum in Rotated Sorted Array (Hard))