follow to "Find Minimum in rotated Sorted Array":
What if duplicates is allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated on 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.
Solution 1: The extension of the minimum value of the rotating array, this time there can be duplicate elements in the array. There is no repeating element in the problem factor group, so judging the size of nums[left] and Nums[mid] can determine whether the [Left,mid] is strictly incremented, and when there are duplicate elements can not be so simple to determine. For example, the two rotations of the array {0,1,1,1,1} {1,0,1,1,1} and {1,1,1,0,1}, the first iteration nums[left]=nums[mid]=nums[right], are not sure [Left,mid] or (Mid, Right] is not ascending, nor does it know whether the minimum element 0 is in [Left,mid] or [mid,right]. Therefore, when the left, mid, right, the exponential group of elements of the same call order lookup algorithm.
classSolution { Public: intFindmin (vector<int>&nums) { intn = nums.size (), left =0, right = N-1, Mid =0; if(N <=1)returnn = =1? nums[0] :0; while(Nums[left] >=Nums[right]) {Mid= (left + right) >>1; if(Nums[left] = = Nums[mid] && Nums[mid] = =Nums[right])return*min_element (Nums.begin () + left, Nums.begin () + Right +1); Else if(Nums[mid] <= nums[right]) right =mid; ElseLeft = mid +1; } returnNums[left]; }};
Solution 2: When the left, mid and right of the index group of elements in the same time, you can move left one bit, skip the same element, so that does not affect the result, because there is another copy of this element exists with the remaining array. Note that the input array has two cases: either Nums[left]<nums[right], when the array is not rotated, can be returned directly, or Nums[left]>=nums[right], when the array is rotated.
classSolution { Public: intFindmin (vector<int>&nums) { intn = nums.size (), left =0, right = N-1, Mid =0; if(n = =0)return 0; while(Left <Right ) { if(Nums[left] < nums[right])returnNums[left]; Mid= (left + right) >>1; if(Nums[left] <Nums[mid]) left= Mid +1; Else if(Nums[left] >Nums[mid]) right=mid; Else++Left ; } returnNums[right]; }};
[leetcode]111. Find Minimum in rotated Sorted Array II rotation minimum value II