题目
Suppose an array sorted in ascending order 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.
The array may contain duplicates.
示例1:
1 | Input: [1,3,5] |
示例2:
1 | Input: [2,2,2,0,1] |
提示:
- This is a follow up problem to Find Minimum in Rotated Sorted Array.
- Would allow duplicates affect the run-time complexity? How and why?
解法
解法一:
库函数
排序,取第一个即可。
JAVA
1 | public int findMin(int[] nums) { |
解法二:
遍历
循环遍历,取最小的一个即可。
JAVA
1 | public int findMin(int[] nums) { |
解法三:
找到最大值和最小值的交界
Java
1 | public int findMin(int[] nums) { |
解法四:
二分查找
这块就不能用题目153的二分查找了。要稍微变形以下。
之前在使用二分查找的时候定义了三个值,low,mid,high。对应的nums数组中数字的关系,总共有6种,A3!。
分别是:
- nums[low] <= nums[mid] <= nums[tail]
- nums[mid] <= nums[tail] <= nums[low]
- nums[tail] <= nums[low] <= nums[mid]
根据题目规则,已排序数组旋转,以下三种是不可能的情况:
- nums[head] <= nums[tail] <= nums[mid]
- nums[mid] <= nums[head] <= nums[tail]
- nums[tail] <= nums[mid] <= nums[head]
JAVA
1 | public int findMin(int[] nums) { |
解法五:
递归
Java
1 | public int findMin(int[] nums) { |