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.
如果存在A[i] > A[i+1]的点,则A[i+1]一定是最小点。
如果不存在这样的点,则在遍历时记录一个min,返回最小的即可。
该方法最坏情况下时间复杂度是O(n),是最navie的方法。
int findMin(vector<int> &num) { //C++ if(num.size() == 1) return num[0]; int min = num[0]; int i = 0; for(int i = 0; i < num.size()-1; i++) { if(num[i]>num[i+1]) return num[i+1]; if(min > num[i]) min = num[i]; } min = (min > num[num.size()-1])?num[num.size()-1]:min; return min; }
public int findMin(int[] A) { //JAVA int L = 0, R = A.length - 1; while (L < R && A[L] >= A[R]) { int M = (L + R) / 2; if (A[M] > A[R]) { L = M + 1; } else if (A[M] < A[L]) { R = M; } else { // A[L] == A[M] == A[R] L = L + 1; } } return A[L]; }
原文地址:http://blog.csdn.net/chenlei0630/article/details/41522747