Find Minimum in Rotated Sorted Array
Suppose a sorted array is rotated at some unknown to you beforehand.
(I. e .,0 1 2 4 5 6 7
Might become4 5 6 7 0 1 2
).
Find the minimum element.
You may assume no duplicate exists in the array.
Solution 1: brute-force method. Use the minimum element function in the algorithm library directly.
The whole vector needs to be traversed.
Class Solution {public: int findMin (vector <int> & num) {if (num. empty () return 0; vector <int>: iterator iter = min_element (num. begin (), num. end (); return * iter ;}};
Solution 2: Use the sorted information. If translation is done, a gap is displayed, that is, the jump from the maximum element to the minimum element. If there is no jump, it means there is no translation.
It can save a lot of time than the previous solution. On average, you do not need to traverse the vector.
Class Solution {public: int findMin (vector <int> & num) {if (num. empty () return 0; else if (num. size () = 1) return num [0]; else {for (vector <int >:: size_type st = 1; st <num. size (); st ++) {if (num [ST-1]> num [st]) return num [st];} return num [0] ;}};
[LeetCode] Find Minimum in Rotated Sorted Array (2 solutions)