How to get the minimum value of the rotated array and the minimum value of the array
I. Question
Moving the first several elements of an array to the end of an array is called the rotation of an array. Input a rotation of a non-descending sorting array and output the smallest element of the rotating array. For example, if an array {3, 4, 5, 1, 2} is a rotation of {1, 2, 3, 4, 5}, the minimum value of this array is 1. NOTE: All given elements are greater than 0. If the array size is 0, return 0.
Ii. Ideas
Binary lookup: the most obvious thing here is binary lookup. The principle of binary lookup is not much, but note that when writing binary lookup code, when the size of the queried array is 2, be sure to note that because this is mid = 0, front = 0, end = 1, no matter how you look for it, it is easy to fall into an endless loop, therefore, when the size of an array is 0, 1, or 2, it is best to make a separate judgment.
Iii. Code
// Binary Search idea int minNumberInRotateArray1 (vector
RotateArray) {if (rotateArray. empty () return 0; else if (rotateArray. size () = 1) return rotateArray [0]; else if (rotateArray. size () = 2) {if (rotateArray [0]> rotateArray [1]) return rotateArray [1]; else return rotateArray [0];} int p1 = 0, p2 = rotateArray. size ()-1; int mid = p1 + (P2-P1)/2; // correct order if (rotateArray [p1] <= rotateArray [mid]) & (rotateArray [mid] <= rotateArray [p2]) return rotateArray [p1]; else if (rotateArray [p1]> rotateArray [mid]) // minimum value in the first half {vector
Vec (rotateArray. begin (), rotateArray. begin () + mid + 1); return minNumberInRotateArray1 (vec);} else {vector
Vec (rotateArray. begin () + mid, rotateArray. end (); return minNumberInRotateArray1 (vec );}}
Note the following points when writing code:
1. The range operation of the vector is the left closed range.
2, vector size is M, then the actual use of subscript access can only get the (M-1) of the lower value.
----------------
To understand this question separately, you can also directly traverse the Array
int minNumberInRotateArray(vector
rotateArray) { if(rotateArray.empty()) return 0; int p=0; for(int i=0;i
rotateArray[i+1]) { p = i+1; break; } } return rotateArray[p];}