码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Find Minimum in Rotated Sorted Array II

时间:2015-10-22 06:48:19      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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];
    }
}

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

 

 

Leetcode Find Minimum in Rotated Sorted Array II

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4899736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!