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