标签:
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.
思路:
设数组num, 左边起点为l,右边终点为r, m=(l+r)/2
1. 如果num[l] < num[r];说明从l到r有序,则min=num[l];
2. 如果num[l] > num[r];说明发生了折叠;
若num[m]<=num[r];则在l~m间查找最小值;
若num[m]>=num[l];则在m+1~r间查找最小值;
3. 如果num[l] == num[r];
若num[m] < num[r];在l~m间查找最小值;
若num[m] > num[l];在m+1~r间查找最小值
若num[m] == num[l];此时二分查找失效,需要遍历从l~r整个数组(如[3,3,3,3,3,3,3,1,3]和[3,3,1,3,3,3,3,3,3])
代码如下:
public int findMin(int[] num) { return findMin(num, 0, num.length-1); } public int findMin(int[] num ,int l, int r) { if(l == r) return num[l]; if(l > r) return 0; int m = (l+r) / 2; if(num[l] == num[r] && num[r] == num[m]) { int min = num[l]; for(int i=l+1; i<=r; i++) { if(num[i] < min) min = num[i]; } return min; } else if(num[l] < num[r]) { return num[l]; } else { if(num[m] <= num[r]) return findMin(num, l, m); else if(num[m] >= num[l]) return findMin(num, m+1, r); } return 0; }
LeetCode-154 Find Minimum in Rotated Sorted Array II
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4330683.html