Problem:
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.
Analysis:
Solutions:
C++:
int findMin(vector<int>& nums) {
if(nums.empty())
return -1;
if(nums.size() == 1)
return nums[0];
if(nums.size() == 2)
return nums[0] >= nums[1] ? nums[1] : nums[0];
int start = 0;
int end = nums.size() - 1;
for(; start < end; ++start) {
if(nums[start] != nums[start + 1])
break;
}
for(; end > start; --end) {
if(nums[end] != nums[start])
break;
}
if(start == end)
return nums[end];
if(nums[start] < nums[end])
return nums[start];
while(start < end) {
if(start == end - 1)
break;
int mid = (start + end) / 2;
int left = mid;
int right = mid;
for(; left > start; --left) {
if(nums[left - 1] != nums[left])
break;
}
for(; right < end; ++right) {
if(nums[right + 1] != nums[right])
break;
}
if(nums[mid] < nums[left - 1] && nums[mid] < nums[right + 1])
return nums[mid];
else if(nums[mid] < nums[start] && nums[mid] <= nums[end])
end = left;
else if(nums[mid] > nums[start] && nums[mid] >= nums[end])
start = right;
}
return nums[start] >= nums[end] ? nums[end] : nums[start];
}
Java
:
Python: