https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
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.
public int findMin(int[] num)
正如描述中所说,这一题是Find Minimum in Rotated Sorted Array加了一条件,就是允许了数组出现重复数字。
加了这一个条件,logn的解就成为了不可能,思考一下这样一个数组, 1,1,1,2,1,1,1,1,1,1。怎么binary search你都没办法真正的排除掉是哪一边是sorted哪一边是rotated sorted。
所以这个时候Binary Search只是用来在O(n)的基础上优化一下而已。
基本原理和之前相同,还是首先要识别出某一边是否sorted array或者rotated sorted array,但问题在于,这种判断在允许重复的情况下,会出现三种结果,1.是sorted。2.是rotated。3.不知道。。。对,就是不知道。。譬如说刚才那个数组,我要判断中间右边或者左边的数组是sorted还是rotated,是判断不出来的。这种情况下只能将尾巴或者头向中间移动来缩小范围。根据上述判断,再加上我们在find minimum in rotated sorted array里面更新过的算法,得到下面这个代码:
public int findMin(int[] num) {
int head = 0, tail = num.length - 1;
while(head < tail){
int mid = (head + tail) / 2;
if(num[mid] < num[tail])
tail = mid;
else if(num[mid] > num[tail])
head = mid + 1;
else
tail--;
}
return num[head];
}
2018-01-30 Updated: 加了一个条件,我认为performance会相对好一些
public int findMin(int[] nums) {
int head = 0, tail = nums.length - 1;
while (head <= tail) {
int mid = (head + tail) / 2;
if (nums[mid] < nums[(mid - 1 + nums.length) % nums.length]) {
return nums[mid];
} else if (nums[mid] > nums[tail]) {
head = mid + 1;
} else if (nums[mid] < nums[tail]) {
tail = mid - 1;
} else {
tail--;
}
}
return nums[head];
}