【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.,
Find the minimum element.
You may assume no duplicate exists in the array.
思路:
有序数组旋转后,如果mid元素比low大,则左边有序,右边乱序,考虑最左元素是否最小元素,并继续考察右边。如果mid小于low,则左边乱序,右边有序,考虑mid是否是最小元素,并继续考察左边,调整mid。
算法:
题目:
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7might 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; }
相关文章推荐
- cygwin
- 失效对象
- Unicode UTF-8 UTF-16编码问题
- linux命令
- C# WinForm获取程序所在路径方法
- Android调用WebService(图文教程)
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 支付宝集成过程详解——运行DEMO
- 8天学通MongoDB——第四天 索引操作
- online_judge_1005
- NSData、 UIImage、ALAsset之间的关系和转化