lintcode-medium-Find Minimum in Rotated Sorted Array

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.

 

Given [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];
            
            int mid = left + (right - left) / 2;
            
            if(num[left] < num[mid])
                left = mid + 1;
            else
                right = mid;
        }
        
        return Math.min(num[left], num[right]);
    }
}

 

posted @ 2016-03-20 14:18  哥布林工程师  阅读(143)  评论(0编辑  收藏  举报