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

题意:给出一个旋转后的数组,求该数组中的最小值。

思路:用二分法的递归形式。(1)数组只有一个元素,这个就是最小值 。(2)数组中有两个元素,求这两个的最小值。(3)如果第一个元素小于最后一个元素,说明这个区间的数组是从小到大排序的。最左边的就是最小值。(4)求这个区间的中间位置mid,然后递归计算[low, mid]和[mid+1,high]的最小值 。

代码如下:

class Solution
{
    private int findMin(int[] nums, int low, int high)
    {
        if (low == high) return nums[low];
        else if (1 == high - low)
        {
            return Math.min(nums[low], nums[high]);
        }
        else
        {
            if (nums[low] <  nums[high]) return nums[low];
            int mid = (low + high) >> 1;
            int min1 = findMin(nums, low, mid);
            int min2 = findMin(nums, mid + 1, high);

            return Math.min(min1, min2);
        }
    }
    public int findMin(int[] nums)
    {
        int high = nums.length - 1;
        return findMin(nums, 0, high);
    }
}

解法二:

class Solution {
    public int findMin(int[] nums)
    {
        int left = 0, right = nums.length - 1;
        while (left < right)
        {
            int mid = (left + right) >> 1;
            if (nums[mid] < nums[right])
            {
                right = mid;
            }
            else if (nums[mid] > nums[right])
            {
                left = mid + 1;
            }
        }

        return nums[left];
    }
}


你可能感兴趣的:(LeetCode Find Minimum in Rotated Sorted Array)