Question
Follow up for “Find Minimum in Rotated Sorted Array”:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
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.
The array may contain duplicates.
本题难度Hard。
二分查找法
【复杂度】
时间 O(N) 空间 O(N) 递归栈空间
【思路】
这道题难点就在于有重复数。与[LeetCode]Find Minimum in Rotated Sorted Array的思路差不多,其实只要增加对于nums[r]==nums[mid]
的情况处理:让r
向左移动,直到mid==r||nums[r]!=nums[mid]
,然后再继续递归即可。中心思路就是抛弃多余的重复数(不是全部抛弃,有可能重复数就是最小值)。
【代码】
public class Solution {
public int findMin(int[] nums) {
return helper(0,nums.length-1,nums);
}
private int helper(int l,int r,int[] nums){
//base case
if(r==l)return nums[l];
int mid=(l+r)/2;
if(nums[r]>nums[mid])return helper(l,mid,nums);
//addtional case
if(nums[r]==nums[mid]){
while(mid!=r&&nums[r]==nums[mid])r--;
return helper(l,r,nums);
}else
return helper(mid+1,r,nums);
}
}