Title Descriptionmoves the first element of an array to the end of the array, which we call the rotation of the array. Enter a rotation of a non-descending 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. Note: All elements given are greater than 0, and if the array size is 0, return 0. problem-solving ideas: Because the rotation of the two sub-arrays are ordered, so do not need to fully traverse the results, using the method of two-point lookup to solve; Note special cases left = middle = right, can only be processed by traversal
1#include <iostream>2#include <vector>3 using namespacestd;4 //For example, 12345 of the rotated array 34512 This class of the left first value is equal to the right because each sub-array is ordered, so find Logn with two points5 //For example 01111 of the rotation of the array 11101 10111 This first value = middle Value = The last value requires special handling can only traverse N6 classSolution {7 Public:8 intMinnumberinrotatearray (vector<int>Rotatearray) {9 intn =rotatearray.size ();Ten if(n==0) One return 0; A intIndex1 =0; - intINDEX2 = n1; - intIndexmid =index1; the while(rotatearray[index1]>=Rotatearray[index2]) - { - if(Index2-index1 = =1)//When a difference is found, it is the search cutoff condition - { +Indexmid =Index2; - Break; + } AIndexmid = (INDEX1+INDEX2)/2; at if(Rotatearray[index1] = = Rotatearray[index2] && rotatearray[index1] = = Rotatearray[indexmid])//Special Handling - { - returnMininorder (ROTATEARRAY,INDEX1,INDEX2); - } - if(Rotatearray[indexmid]>=rotatearray[index1])//The median value is greater than the left value and the minimum value is on the right - { inIndex1 =Indexmid; - } to Else if(Rotatearray[indexmid] <=rotatearray[index2])//median value less than right value minimum value on left + { -Index2 =Indexmid; the } * } $ returnRotatearray[indexmid];Panax Notoginseng - } the intMininorder (vector<int> Rotatearray,intIndex1,intindex2) + { A intresult =Rotatearray[index1]; the for(inti=index1+1; i<=index2;i++) + { - if(rotatearray[i]<result) $ { $result =Rotatearray[i]; - } - } the returnresult; - }Wuyi }; the intMain () - { Wuvector<int>A; -A.push_back (3); AboutA.push_back (4); $A.push_back (5); -A.push_back (1); -A.push_back (2); - solution S; A intresult =S.minnumberinrotatearray (a); +cout<<"The min of 12345 is"<<result<<Endl; the -vector<int>b; $B.push_back (1); theB.push_back (0); theB.push_back (1); theB.push_back (1); theB.push_back (1); -result =S.minnumberinrotatearray (b); incout<<"The min of 01111 is"<<result<<Endl; the return 0; the}
Output Result:
6, the sword refers to the offer--rotation array minimum number