首页 > 代码库 > [LeetCode]154 Find Minimum in Rotated Sorted Array II

[LeetCode]154 Find Minimum in Rotated Sorted Array II

https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/

http://blog.csdn.net/linhuanmars/article/details/40449299

public class Solution {
    public int findMin(int[] num) {
        
        // Solution A:
        // return findMin_Iteration(num);
        
        // Solution B:
        return findMin_Recursion(num, 0, num.length - 1);
    }
        
    ////////////////
    // Solution A: Iteration
    //
    private int findMin_Iteration(int[] num)
    {
        int lo = 0;
        int hi = num.length- 1;
        int mid = 0;

        while(lo < hi) {
            mid = lo + (hi - lo) / 2;

            if (num[mid] > num[hi]) {
                lo = mid + 1;
            }
            else if (num[mid] < num[hi]) {
                hi = mid;
            }
            else { // when num[mid] and num[hi] are same
                hi--;
            }
        }
        return num[lo];
    }

    ////////////////
    // Solution B: Recursion
    //
    private int findMin_Recursion(int[] n, int low, int high)
    {
        if (low == high)
            return n[low];
        
        if (low + 1 == high)
            return Math.min(n[low], n[high]);
            
        int mid = low + (high - low) / 2;
        
        if (n[low] < n[mid] && n[low] < n[high])
        {
            return findMin_Recursion(n, low, mid);
        }
        else if (n[low] > n[mid] && n[low] > n[high])
        {
            return findMin_Recursion(n, low, mid);
        }
        else // I don‘t know
        {
            return findMin_Recursion(n, low + 1, high);
        }
    }
}


[LeetCode]154 Find Minimum in Rotated Sorted Array II