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.
Hide TagsArray Binary Search
Modify two points on the basis of http://www.cnblogs.com/diegodu/p/4576831.html:
1. while (Low < high && A[low] > A[high])---> When (Low < high && A[low] >= A[high]) In the repeating element:
2, in the absence of duplicate elements, the middle element is equal to the first element, indicating that there are only two elements, low and high each point to one.
Because the size relationship is limited in the while loop, returning Nums[high] is the minimum value.
However, when there are duplicate elements, the condition does not mean that there are only two elements that have a total of low and high pointing.
Instead, it indicates that the element with the low point is duplicated, so delete one, low + +.
The last reason to return is A[low], because A[low] has returned the lower boundary that contains the pivot, and low has been moving.
Once the A[low] < A[high is found, the next boundary is located, so return to A[low],
Also, if the array is ordered, return directly to A[low]
classSolution { Public: intFindmin (vector<int>&A) {intLow =0; intHigh = A.size ()-1; intMID =0; //A[low] > A[high] Ensure the pivot is between low and high while(Low < High && A[low] >=A[high]) {Mid= (low + high)/2; cout<<"low\t"<< low<<Endl; cout<<"high\t"<< High <<Endl; cout<<"mid\t"<< mid<<Endl; if(A[low] < A[mid])//pivot is in bottom half, mid can ' t be lowest{ Low= Mid +1; } Else if(A[low] = = A[mid])//duplicates elements, just remove one{ Low++; } Else //Pivot is in first half, mid may be lowest{ High=mid; } } returnA[low]; }};
[Leetcode] Find Minimum in rotated Sorted Array II