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.
这道题跟Search in Rotated Sorted Array这道题很像,区别在于这道题不是找一个目标值,而是找最小值。所以与那道题的思路类似又有区别。类似在于同样是用binary search找目标区域,通过左边界和中间的大小关系来得到左边或者右边有序。区别在于这一次迭代不会存在找到target就终止的情况,iteration要走到 l > r 的情况才停止。所以这一次思路是确定中点哪一边有序之后,那一边的最小值就是最左边的元素。用这个元素尝试更新全局维护的最小值,然后迭代另一边。这样子每次可以截掉一半元素,所以最后复杂度等价于一个二分查找,是O(logn),空间上只有四个变量维护二分和结果,所以是O(1)。
1 class Solution { 2 public int findMin(int[] nums) { 3 int res = Integer.MAX_VALUE; 4 int l = 0, r = nums.length - 1; 5 while (l <= r) { 6 int m = (l + r) / 2; 7 if (nums[m] >= nums[l]) { 8 // rotation is happened in the latter half 9 // [l, m] is in order 10 res = Math.min(res, nums[l]); 11 l = m + 1; 12 } 13 else { 14 // rotation is happened in the first half 15 // [m, r] is in order 16 res = Math.min(res, nums[m]); 17 r = m - 1; 18 } 19 } 20 return res; 21 } 22 }