154. Find Minimum in Rotated Sorted Array II
(i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
有序数组,不管怎么循环移动,找到最大值,就可以找到最小值。
解法1:双指针,当前大于后,说明前指针是最大值,后是最小值。时间复杂度位n。
解法2:二分查找。
有序数组n,index low high,找到中间index mid,如果n[mid] < n[high],说明无序的在左边;如果n[mid] > n[high],说明无序的在右边。逐步缩小范围。
public static int findMin(int[] nums) { int low = 0; int high = nums.length - 1; while(low < high) { int mid = (high + low) >> 1; if(nums[mid] < nums[high]) { high = mid; } else if(nums[mid] > nums[high]) { low = mid + 1; } else { high--; } } return nums[low]; }
public static int findMax(int[] nums) { int low = 0; int high = nums.length - 1; while(low < high) { int mid = (high + low) >> 1; if(nums[mid] < nums[high]) { high = mid - 1; } else if(nums[mid] > nums[high]) { low = mid; } else { low++; } } return nums[low]; }
看起来这个high-- low++没啥差别。如果没有重复数字的话,确实没差别,有重复的话,极端情况下,上面的代码也找不出来结果。
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/?orderBy=most_votes