Leetcode Find Minimum in Rotated Sorted Array II

Suppose a sorted array 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.


解题思路:

Leetcode Find Minimum in Rotated Sorted Array 的区别只是有重复数字。

方法一:推荐用binary search.  O(logn)

当A[mid] = A[end]时,无法判断min究竟在左边还是右边。

但可以肯定的是可以排除A[end]:因为即使min = A[end],由于A[end] = A[mid],排除A[end]并没有让min丢失。所以增加的条件是:
A[mid] = A[end]:搜索A[start : end-1]
 
画图解决
 
方法二:直接观察发现最小值就是某值比前面的那个数小,就是最小值。也对。当然复杂度是O(n). 还是方法一更好。代码和之前那题没有任何变化。不用这个方法!

Java code:
1. binary search
public class Solution {
    public int findMin(int[] nums) {
       int left = 0, right = nums.length-1;
       while(left < right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] < nums[right]){
                right = mid;
            }else if(nums[mid] > nums[right]){
                left =  mid+1;
            }else {
                right--;
            }
        }
        return nums[left];
    }
}

1.2 九章算法模板方法 2016.01.18

public class Solution {
    public int findMin(int[] nums) {
         if(nums == null || nums.length == 0) {
            return -1;
        }
        int start = 0, end = nums.length-1;
        int mid;
        while(start + 1 < end) {
            mid = start + (end - start) / 2;
            if(nums[mid] < nums[end]) {
                end = mid;
            }else if (nums[mid] > nums[end]) {
                start = mid;
            }else {
                end--;
            }
        }
        if(nums[start] < nums[end]) {
            return nums[start];
        }else {
            return nums[end];
        }
    }
}

2. 

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

Reference:

1. http://bangbingsyb.blogspot.com/2014/11/leecode-find-minimum-in-rotated-sorted.html

 

 

posted @ 2015-10-22 04:25  茜茜的技术空间  阅读(232)  评论(0编辑  收藏  举报