您的位置:首页 > 其它

【Leetcode】Find Minimum in Rotated Sorted Array

2015-12-04 16:18 176 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: