【Leetcode】Find Minimum in Rotated Sorted Array

题目链接:https://leetcode.com/problems/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.

思路:

有序数组旋转后,如果mid元素比low大,则左边有序,右边乱序,考虑最左元素是否最小元素,并继续考察右边。如果mid小于low,则左边乱序,右边有序,考虑mid是否是最小元素,并继续考察左边,调整mid。

算法:

	public int findMin(int[] nums) {
		int min = nums[0];
		int l = 0, h = nums.length - 1, m = 0;
		while (l <= h) {
			m = (l + h) / 2;
			if (nums[m] >= nums[l]) {//右边乱序
				min = Math.min(nums[l], min);//左边单增,考察最左元素是否最小
				l = m + 1;//考虑右边
			} else {//左边乱序
				min = Math.min(nums[m], min);
				h = m - 1;
			}
		}
		return min;
	}


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