问题描述:
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 an array sorted in ascending order 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.
解题思路:跟上一道题一样,也是在翻转过的排序数组里面找到一个最小值,不同点是元素有重复。这个时候二分法就有些问题,比如:[4 4 4 1 4 4]. 二分的值4和首元素最后元素相等,没法取舍哪一块,我们只能寻求线性方法。但是这种情况是小概率的,大概率情况下我们依旧可以采用二分法。代码如下:
class Solution {
public:
int findMin(vector<int>& nums) {
int s = 0, t = nums.size()-1;
int k = nums[t];
if(nums[s] < k) return nums[s];
if(nums[s] = k){
int mid = ((s+t)>>1);
if(nums[mid] == k) return findline(nums);
else if(nums[mid] > k) s = mid+1;
else t = mid;
k = nums[mid];
}
while(s<t){
int mid = ((s+t)>>1);
if(nums[mid] >= k) s = mid+1;
else t = mid;
}
return nums[s];
}
private:
int findline(vector<int>& nums){
for(int i = 1; i<nums.size(); i++){
if(nums[i] < nums[i-1])
return nums[i];
}
return nums[0];
}
};
findline是一个线性的寻找最小值方法,当且仅当首元素==最后元素==中间元素才退化成线性方法。除此之外都可以用二分方法。因此主要问题在中间的一步nums[s] == k的讨论上。时间复杂度O(N).