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.
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.
问题分析:这个题目和上个题目的区别在于这里允许数组重复。需要区别处理的部分就是上题代码中的相等的情况,当出现middle和low位置的元素相等的时候,我们无法判断最小元素是处于前部分还是后部分,解决办法就是遍历整个数组寻找最小元素,实现代码如下:
class Solution {
public:
int findMin(vector<int>& nums) {
int size=nums.size();
if(size==1) return nums[0];
int low=0,high=size-1,middle=0;
while(nums[low]>=nums[high]){
if(high-low==1) return nums[high];
middle=(low+high)/2;
if(nums[middle]>nums[low]){
low=middle;
}else if(nums[middle]<nums[low]){
high=middle;
}else{
int minNum=nums[low];
for(int i=low;i<=high;i++){
if(minNum>nums[i]) minNum=nums[i];
}
return minNum;
}
}
return nums[middle];
}
};