Suppose a sorted array is rotated on some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Find the minimum element.
Assume no duplicate exists in the array.
The minimum value of this search for an ordered array of rotations must not be found by directly traversing the entire array, which is too simple and rough, so that spin does not spin. You should consider narrowing the time complexity from simple rough O (n) to O (LGN), when the binary search method emerges in the mind.
First of all to determine whether this ordered array is rotated, by comparing the first and last number of the size, if the first number is small, there is no rotation, directly return this number. If the first number is large, you need to search further. We define left and right two pointers pointing to the beginning and end respectively, and also to find the middle number, and then compared with the number of left, if the middle of the number of large, then continue to find the second half of the two-part array, and vice-versa to find the first half segment. The termination condition is that when the left and right two pointers are adjacent, the small one is returned. The code is as follows:
classSolution { Public: intFindmin (vector<int> &num) { intleft =0, right = Num.size ()-1; if(Num[left] >Num[right]) { while(Left! = (Right-1)) { intMid = (left + right)/2; if(Num[left] < Num[mid]) left =mid; Elseright =mid; } returnmin (Num[left], num[right]); } returnnum[0]; }};
Find Minimum in rotated Sorted array looks for the minimum value of the rotated ordered arrays