The title describes moving 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.//The non-diminishing here is not disorderly order, but also increment, but the process of increment can have the same number
#include <iostream>#include<vector>using namespacestd;classSolution { Public: intMinnumberinrotatearray (vector<int>Rotatearray) { intTotallen =rotatearray.size (); if(0==Totallen) { return 0; }Else if(1==Totallen) { returnrotatearray[0]; } Else{ intVethead =0; intVettail = Totallen-1; intVetlen =Totallen; intVetmid = (Vethead + vettail)/2; while(Rotatearray[vethead] >= Rotatearray[vettail])//shrinkage range at this time { if((Vettail-vethead) <=1){//consider the case of excessive shrinkage, you need to traverse backward such as {2,2,2,2,2,2,2,1,2}, may shrink to the middle of two 2, and 1 at this time in the back, so need to traverse backwards if(Rotatearray[vethead] = = Rotatearray[vettail] && Rotatearray[vethead] >=Rotatearray[vetmid]) { inti =Vettail; intj = Vettail +1; while(Rotatearray[i] <=Rotatearray[j]) {i++; J++; } returnRotatearray[j]; //return rotatearray[vettail]; } } if(Rotatearray[vethead] >= Rotatearray[vetmid]) {//Shrink leftVettail =Vetmid; Vetmid= (Vethead + vettail)/2; Continue; } if(Rotatearray[vethead] < Rotatearray[vetmid]) {//Shrink RightVethead =Vetmid; Vetmid= (Vethead + vettail)/2; Continue; } } returnRotatearray[vethead]; } }};voidMain () {solution S; //vector<int> va = {Ten, one, one, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};vector<int> VA = {3,4,5,6,7,8,9,Ten, One, A,0,1,2 }; //vector<int> va = {2,2,1,2,2,2}; //vector<int> va = {1, 2, 2, 2, 2, 2}; intresult =S.minnumberinrotatearray (VA); cout<< result <<Endl; System ("Pause");}
This algorithm has a lot of pits, and some boundary conditions need to be considered. But eventually it passed:
"The point of the sword" algorithm--the minimum number of "rotation array"