Title: Moving a number of elements at the beginning of an array to the end of the data, which we call
The rotation of the array. Enter a rotation of an incrementally sorted array, output the rotated array
The smallest element. For example, the array {3,4,5,1,2} is a rotation of {1,2,3,4,5}, which
The minimum value of the array is 1.
This problem can be used similar to the idea of binary search, the algorithm ideas are as follows:
1. Suppose there is a rotating array A, we set two indexes P1,p2
2.p1 points to the first element of an array, P2 points to the last element of the array
3. Take P3 as an intermediate element in an array
4. Compare the elements pointed to by the P3 with the P1,P2. If P3>P1, it means the first half
If the subarray is an incremented array, the minimum value must be in the subsequent half increment of the subarray,
If P3<P2, the minimum value must be located before P3,
5. When p3>p1, we let p1=p3, when P3<P2,P2=P3
6. Repeat step 4 until p1,p2 adjacent, the element that P2 points to is the minimum value
The implementation is as follows:
1#include <iostream>2 using namespacestd;3 4 intMin (int* Nums,intlength)5 {6 intleft=0;7 intright=length-1;8 intmid;9 while((right-left)! =1)Ten { OneMid= (left+right)/2; A if(nums[mid]>Nums[left]) - { -left=mid; the } - if(nums[mid]<Nums[right]) - { -right=mid; + } - } + returnNums[right]; A } at - - intMain () - { - - intnums[Ten]={6,7,8,9,Ten,1,2,3,4,5}; in intNumssize=Ten; - intMinnumber; toMinnumber=Min (nums,numssize); +cout<<"The min number of array is:"<<minnumber<<Endl; - return 0; the}
Run:
As the sword says in the offer book, we also need two things:
1. When the initial nums[left]=nums[right],left=0,right=length-1;
, the sorted array is actually not rotated, but it can also be called rotation,
Rotated 0 elements. The smallest number is the first number that is nums[0].
2. When Nums[left]=nums[mid]=nums[right], such as sort array 0,1,1,1,1
The rotation is 1,1,1,0,1 this time we can not use the above binary find method to narrow the minimum value
, then in this case we need to look for it in a sequential way.
I hope my notes will inspire you.
The offer-of the Sword 8. Minimum number of rotation array