LeetCode 153 - 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.

You may assume no duplicate exists in the array.

Solution 1:

public int findMin(int[] num) {
    int start = 0, end = num.length-1;
    int min = num[0];
    while(start <= end) {
        int mid = (start + end) / 2;
        if(num[mid] <= num[end]) { // 7 0 1 2 4 5 6, min位于上升沿左侧
            end = mid - 1;
        } else { // 4 5 6 7 0 1 2, min位于左侧上升沿与右侧上升沿之间
            start = mid + 1;
        }
        min = Math.min(min, num[mid]);
    } 
    return min;
}

 

Solution 2:

这是我所见到的最简单的解法了,源自StackOverFlow。(注:这个方法在有重复元素的情况下无效)

public int findMin(int[] num) {
    int l = 0, h = num.length-1;
    while(num[l] > num[h]) {
        int m = (l + h) / 2;
        if(num[m] > num[h]) { // 4 5 6 7 0 1 2, min位于左侧上升沿与右侧上升沿之间
            l = m + 1;
        } else { // 7 0 1 2 4 5 6, min位于上升沿左侧
            h = m;
        }
    } 
    return num[l];
}

 

下面的版本是能够处理有重复元素的情况:

public int findMin(int[] num) {  
    int l = 0, h = num.length-1;  
    while(l < h && num[l] >= num[h]) {  
        int m = (l + h) / 2;  
        if(num[m] > num[h]) { // 4 5 6 7 0 1 2, min位于左侧上升沿与右侧上升沿之间  
            l = m + 1;  
        } else if(num[m] < num[h]) { // 7 0 1 2 4 5 6, min位于上升沿左侧  
            h = m;  
        } else {
            l++;
        }
    }
    return num[l];  
} 

 

Reference:

http://stackoverflow.com/questions/8532833/find-smallest-number-in-sorted-rotatable-array

你可能感兴趣的:(Binary search)