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.
This search for the minimum value of the rotated ordered repeating array is an extension to the previous problem, and when there are a large number of duplicate numbers in the array, it destroys the mechanism of the binary lookup method, we cannot get the time complexity of O (LGN) and will return to the simple rough O (n), such as the following two cases:
{2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 1, 2, and {2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2}, we found that when the first and last numbers, and the middle one, were all equal, the binary search collapsed, Because it can't tell whether to go to the left or the right half. In this case, we can only go back to the primitive kind of simple rough way, the entire array to the beginning and end of the first to find out the smallest one. The code is as follows:
classSolution { Public: intFindmin (vector<int> &num) { if(Num.size () <=0)return 0; if(num.size () = =1)returnnum[0]; intleft =0, right = Num.size ()-1; if(Num[left] >Num[right]) { while(Left! = (Right-1)) { intMid = (left + right)/2; if(Num[left] <= num[mid]) left =mid; Elseright =mid; } returnmin (Num[left], num[right]); } Else if(Num[left] = =Num[right]) { intres = num[0]; for(inti =1; I < num.size (); ++i) {res=min (res, num[i]); } returnRes; } returnnum[0]; }};
Find Minimum in rotated Sorted array 2 finds the smallest value of the rotated ordered array of two