标签:
Description:
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.
Code:
1 int findMinElement(vector<int>& nums, int indexLeft, int indexRight) 2 { 3 if (indexLeft < indexRight) 4 { 5 if ( nums[(indexLeft+indexRight)/2] < nums[indexRight]) 6 return findMinElement(nums, indexLeft, (indexLeft+indexRight)/2); 7 else if ( nums[(indexLeft+indexRight)/2] > nums[indexRight]) 8 return findMinElement(nums, (indexLeft+indexRight)/2+1, indexRight); 9 else 10 {//此时不能判最小值在左边还右边,遍历判断 11 int result = nums[indexLeft]; 12 for (int i = indexLeft+1; i <= indexRight; i++) 13 { 14 if ( nums[i] < result) 15 result = nums[i]; 16 } 17 return result; 18 } 19 } 20 else 21 return nums[indexLeft]; 22 } 23 int findMin(vector<int>& nums) { 24 return findMinElement(nums, 0, nums.size()-1 ); 25 }
Find Minimum in Rotated Sorted Array II
标签:
原文地址:http://www.cnblogs.com/happygirl-zjj/p/4592202.html