Find Minimum in rotated Sorted array 2 Finding the smallest value of the rotated ordered array two

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.