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.
Analyse: add the situation where nums[mid] == nums[left].
Runtime: 8ms
1 class Solution { 2 public: 3 int helper(vector<int>& nums, int left, int right){ 4 int mid = left + (right - left) / 2; 5 6 if(left == right) return nums[left]; 7 if(right - left == 1) return min(nums[left], nums[right]); 8 9 if(nums[left] < nums[right]) //didn‘t rotate 10 return nums[left]; 11 else if(nums[mid] < nums[left]) 12 return helper(nums, left, mid); 13 else if(nums[mid] > nums[left]) 14 return helper(nums, mid, right); 15 else{ 16 int a = helper(nums, mid, right); 17 int b = helper(nums, left, mid); 18 return min(a, b); 19 } 20 } 21 22 int findMin(vector<int>& nums) { 23 if(nums.size() == 0) return 0; 24 return helper(nums, 0, nums.size() - 1); 25 } 26 };
Find Minimum in Rotated Sorted Array II
原文:http://www.cnblogs.com/amazingzoe/p/4873370.html