Minimum number of rotated array

Source: Internet
Author: User

Title: Move a number of elements at the beginning of an array to the end of the array, which we call the rotation of the array. Enter a rotation of a non-descending sequence that outputs the smallest element of the rotated array. For example, the array {3,4,5,1,2} is a rotation of {1,2,3,4,5}, and the minimum value of the array is 1.

Idea: The first to give the rotation of the array of books locally ordered, it can be thought of using binary search to solve the performance of optimizing linear lookups. The solution for this problem is similar to a binary lookup, which sets three pointers, Left,right,mid. When mid>=left indicates the minimum number on the right, when Mid<=right is indicated on the left. But in the left==right==mid can not be judged, only sequential search. Boundary conditions require special treatment.

Implementation code:

Importjava.util.ArrayList; Public classSolution { Public intMinnumberinrotatearray (int[] Array) {        if(Array = =NULL|| Array.Length = = 0)            return0; intLen =Array.Length; intleft = 0, right = len-1, mid = 0;  while(Left <=Right ) {Mid= (left + right)/2; if(left + 1 = =Right )returnArray[right];//only two left .            if(Array[right] >Array[left]) {                returnArray[left]; }            if(Array[mid] = = Array[left] && Array[mid] = =Array[right]) {                returnmin (array, left, right); }            Else if(Array[mid] >=Array[left]) { Left=mid; }            Else{ Right=mid; }        }        returnArray[mid]; }         Public intMinint[] Array,intLeftintRight ) {        intMin =Integer.max_value;  for(intI=left; i<=right; i++) {            if(Array[i] <min) min=Array[i]; }        returnmin; }}

Minimum number of rotated array

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.