Find Minimum in rotated Sorted array looking for the minimum value of the rotated ordered arrays

Source: Internet
Author: User

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.

Assume no duplicate exists in the array.

The minimum value of this search for an ordered array of rotations must not be found by directly traversing the entire array, which is too simple and rough, so that spin does not spin. You should consider narrowing the time complexity from simple rough O (n) to O (LGN), when the binary search method emerges in the mind.

First of all to determine whether this ordered array is rotated, by comparing the first and last number of the size, if the first number is small, there is no rotation, directly return this number. If the first number is large, you need to search further. We define left and right two pointers pointing to the beginning and end respectively, and also to find the middle number, and then compared with the number of left, if the middle of the number of large, then continue to find the second half of the two-part array, and vice-versa to find the first half segment. The termination condition is that when the left and right two pointers are adjacent, the small one is returned. The code is as follows:

classSolution { Public:    intFindmin (vector<int> &num) {        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]); }        returnnum[0]; }};

Find Minimum in rotated Sorted array looks for the minimum value of the rotated ordered arrays

Related Article

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.