Find Minimum in Rotated Sorted Array

O(logN)

There are two section: 

1) increase array which the first element is larger than end one.

2) the minimum to end

Comparing with the endVal,
1) if a val is larger than endVal, it falls into the first section. Throw array. 

2) if a val is less or equal to end, it falls into the second section. Because we want to get the minimum, so we just need let end equal mid.

Always choose the bench mark in the "keep" section, in this problem, it is the endVal. Because there is a situation which it is not rotated.  

public class Solution {
    /**
     * @param nums: a rotated sorted array
     * @return: the minimum number in the array
     */
    public int findMin(int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) {
            return -1;
        }
        
        int start = 0;
        int end = nums.length - 1;
        int endVal = nums[end];
        
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] > endVal) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        if (nums[start] <= nums[end]) {
            return nums[start];
        }
        if (nums[end] < nums[start]) {
            return nums[end];
        }
        
        return -1;
    }
}

 

posted on 2017-05-04 06:06  codingEskimo  阅读(84)  评论(0编辑  收藏  举报

导航