Sword Point offer interview question: 7. Rotate the minimum number of the array

Source: Internet
Author: User

First, title: the smallest number of rotating arrays

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 an incrementally sorted array, outputting 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.

The most intuitive solution to this problem is not difficult, and we can find the smallest element by traversing the array one at a time. The time complexity of this idea is obviously O (n). But this idea does not take advantage of the characteristics of the input rotation array, and certainly does not reach the interviewer's requirements .

We notice that the rotated array can actually be divided into two sorted sub-arrays, and the elements of the preceding sub-arrays are greater than or equal to the elements of the post-face array. We also note that the smallest element is just the dividing line of these two sub-arrays. in the sorted array we can use the binary lookup method to achieve O (LOGN) lookup .

Second, the idea of solving problems

  Step1. As with the binary lookup method, we use two pointers to point to the first and last element of the array, respectively.

  Step2. Then we can find the elements in the middle of the array:

If the intermediate element is in the preceding increment sub-array, it should be greater than or equal to the element that the first pointer points to. The smallest element in the array should be at the back of the intermediate element. We can point the first pointer to the middle element so that we can narrow the scope of the search . The first pointer after the move is still in the preceding increment sub-array. If the intermediate element is in a subsequent increment of a subarray, it should be less than or equal to the element that the second pointer points to. At this point the smallest element in the array should precede the intermediate element.

  Step3. Next we use the updated two pointers, repeat the new round of search.

In the thought above, the first pointer always points to the element that increments the array earlier, and the second pointer always points to the element that increments the array later. The first pointer will eventually point to the last element of the preceding subarray, and the second pointer will point to the first element of the post-face array. That is, they eventually point to two adjacent elements, and the second pointer points to just the smallest element. This is the condition of the end of the loop.

Using the preceding array {3,4,5,1,2}, for example, shows the process of finding the smallest value in the array:

Third, solve the problem 3.1 code implementation
     Public Static intGetmin (int[] numbers) {        if(Numbers = =NULL|| Numbers. Length <=0)        {            return int.        MinValue; }        intIndex1 =0; intIndex2 = numbers. Length-1; //reasons for initializing Indexmid to index1://once the first number in the array is found to be less than the last number, it indicates that the array is sorted//you can just go back to the first number.        intIndexmid =index1;  while(Numbers[index1] >=Numbers[index2]) {            //if Index1 and Index2 point to the adjacent two numbers,//then index1 points to the last number of the first incrementing Subarray,//Index2 points to the first number in the second Subarray, which is the smallest number in the array            if(Index2-index1 = =1) {Indexmid=Index2;  Break; } Indexmid= (index1 + index2)/2; //Special case: If the subscript is index1, Index2, and Indexmid point to three numbers equal, then only the sequential lookup            if(Numbers[index1] = = Numbers[indexmid] && Numbers[indexmid] = =Numbers[index2]) {                returnGetmininorder (Numbers, index1, index2); }            //narrowing the look -up range            if(Numbers[indexmid] >=Numbers[index1]) {index1=Indexmid; }            Else if(Numbers[indexmid] <=Numbers[index2]) {Index2=Indexmid; }        }        returnNumbers[indexmid]; }     Public Static intGetmininorder (int[] numbers,intIndex1,intindex2) {        intresult =NUMBERS[INDEX1];  for(inti = index1 +1; I <= index2; ++i) {if(Result >Numbers[i]) {Result=Numbers[i]; }        }        returnresult; }

It is important to note that:

(1) The reason for initializing Indexmid to index1: Once the first number in the array is found to be less than the last number, indicating that the array is sorted, the first number can be returned directly.

(2) Special case Analysis: If the subscript is index1, Index2, and Indexmid point to the three numbers equal, it can only be searched sequentially, so a Getmininorder () method is defined here.

3.2 Unit Test

(1) Typical input, a rotation of an array of monotone ascending

    // typical input, a rotation of an array of monotone ascending     [TestMethod]    publicvoid  GetMinNumTest1 ()    {        int [] Array = {34512};        Assert.AreEqual (Program.getmin (array),1);    }

(2) The smallest number that has a repeating number and a number that repeats exactly

    // The smallest number that has a repeating number and the number that repeats exactly     [TestMethod]    publicvoid  GetMinNumTest2 ()    {        int 3 4 5 1 1 2  };         1 );    }

(3) There are duplicate numbers, but the number of repetitions is not the first number and the last number

    // There are duplicate numbers, but the number of repetitions is not the first number and the last number     [TestMethod]    publicvoid  GetMinNumTest3 ()    {        int 3 4 5 1 2 2  };         1 );    }

(4) There are duplicate numbers, and the number of repetitions is exactly the first and last number.

    // There are duplicate numbers, and the number of repetitions is exactly the first number and the last number .     [TestMethod]    publicvoid  GetMinNumTest4 ()    {        int 1 0 1 1 1  };         0 );    }

(5) A monotone ascending array, which rotates 0 elements, that is, the monotonically ascending array itself

    // monotone ascending array, rotated 0 elements, i.e. monotone ascending array itself     [TestMethod]    publicvoid  GetMinNumTest5 ()    {        int 1 2 3 4 5  };         1 );    }

(6) There is only one number in the array

    // There is only one number in the array     [TestMethod]    publicvoid  GetMinNumTest6 ()    {        int 2  };         2 );    }

(7) Robustness test: input null

    // robustness test: Enter null     [TestMethod]    publicvoid  GetMinNumTest7 ()    {        assert.areequal ( Program.getmin (nullint. MinValue);    }

The result of the unit test is as follows:

The Code coverage for unit tests written by the Getmin method has reached 100%:

Zhou Xurong

Source: http://edisonchou.cnblogs.com

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

Sword Point offer interview question: 7. Rotate the minimum number of the 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.