The smallest number of offer_11_ rotating arrays

Source: Internet
Author: User

Title Description

Moves the first element of an array to the end of the array, which we call the rotation of the array. Enter a rotation of an incrementally sorted array, outputting the smallest element of a rotated array.

For example: {3,4,5,1,2} is a rotated array of {1,2,3,4,5}, and the smallest element of the array is 1.

Analysis:

  Method One:

    Because the array's original array is an incrementing array, the array is traversed from the beginning, and the a[i] is less than a[i-1] then the smallest element is found, which is a[i].

1 intFindminnumber (intArr[],intLength) {//arr is an array of rotation, length2      for(intI=1; i<length;i++){3         if(arr[i]<arr[i-1])4             returnArr[i];//found the smallest element5     }6     return-1;//not found, return-17}

Method Two:

With a binary lookup, two pointers point to the first element (P1) and the tail element (P2) of the rotated array, comparing the size of the two pointer intermediate elements (MIDNUM) with the elements at each end.

If P1 is greater than midnum, the element between P1 to Midnum is not moved, the smallest element is in the other half, and P1 points to midnum.

If P1 is less than midnum, the element between P1 to Midnum is changed, the smallest element is in it, and P2 points to midnum.

P2.

Until the last P1 equals P2, the smallest element is found.

1 intFindMinNumber2 (intArr[],intlength) {2     intP1 =0 ;3     intP2 = length-1 ;4     intMid = (P1+P2)/2 ;5      while(p1!=p2) {6         if(arr[p1]>Arr[mid])7         {8P2 =mid;9         }Ten         if(arr[p2]<Arr[mid]) { OneP1 =mid; A         } -     } -     returnARR[P1]; the}

    

The smallest number of offer_11_ rotating 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.