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

lintcode-medium-Find Minimum in Rotated Sorted Array II

时间:2016-03-20 16:10:02      阅读:175      评论: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.

 

Given [4,4,5,6,7,0,1,2] return 0

public class Solution {
    /**
     * @param num: a rotated sorted array
     * @return: the minimum number in the array
     */
    public int findMin(int[] num) {
        // write your code here
        if(num == null || num.length == 0)
            return 0;
        
        int left = 0;
        int right = num.length - 1;
        
        while(left < right - 1){
            if(num[left] < num[right])
                return num[left];
            
            while(left < right - 1 && num[left] == num[left + 1])
                left++;
            while(left < right - 1 && num[right] == num[right - 1])
                right--;
            
            int mid = left + (right - left) / 2;
            
            if(num[left] <= num[mid])
                left = mid + 1;
            else
                right = mid;
        }
        
        return Math.min(num[left], num[right]);
    }
}

 

lintcode-medium-Find Minimum in Rotated Sorted Array II

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5297704.html

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