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.
简译:寻找循环有序数组的最小值,可能存在重复的值。
class Solution {
public:
int _findMin(vector<int> &num, int low, int high) {
if (low == high || num[low] < num[high])
return num[low];
const int mid = low + (high-low)/2;
if (num[low] == num[mid] && num[mid] == num[high]) {
const int left = _findMin(num, low, mid);
if (left < num[mid])
return left;
else
return _findMin(num, mid+1, high);
}
if (num[mid] <= num[high])
return _findMin(num, low, mid);
else
return _findMin(num, mid+1, high);
}
int findMin(vector<int> &num) {
return _findMin(num, 0, num.size()-1);
}
};
Find the minimum element in a sorted and rotated array
附上他的代码,供对照。
// The function that handles duplicates. It can be O(n) in worst case.
int findMin(int arr[], int low, int high)
{
// This condition is needed to handle the case when array is not
// rotated at all
if (high < low) return arr[0];
// If there is only one element left
if (high == low) return arr[low];
// Find mid
int mid = low + (high - low)/2; /*(low + high)/2;*/
// Check if element (mid+1) is minimum element. Consider
// the cases like {1, 1, 0, 1}
if (mid < high && arr[mid+1] < arr[mid])
return arr[mid+1];
// This case causes O(n) time
if (arr[low] == arr[mid] && arr[high] == arr[mid])
return min(findMin(arr, low, mid-1), findMin(arr, mid+1, high));
// Check if mid itself is minimum element
if (mid > low && arr[mid] < arr[mid - 1])
return arr[mid];
// Decide whether we need to go to left half or right half
if (arr[high] > arr[mid])
return findMin(arr, low, mid-1);
return findMin(arr, mid+1, high);
在low, mid, high三点处值相等时,其实不一定非要,两个区间都进行查找。
当在第一个区间已经找到最小值是,第二个区间的查找是可以省掉的。
即,如果第一个区间返回的值,小于mid处的值时,那它一定是最小值。并且第二个区的值一定全部相等。
算法其他区别,见前一篇文档: