Title Description:
To move the first elements of an array to the end of the array, we call it the rotation of the array. Input a rotation of a non subtractive sort array, and output the minimum elements of the rotation array. For example, 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 the given elements are greater than 0. If the array size is 0, please return 0.
Solution 1:
The time complexity is O (n).
Reference source 1:
class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { if (rotateArray.size() == 0) return 0; for (int i = 0; i < rotateArray.size()-1; i++) { if (rotateArray[i] > rotateArray[i + 1]) { return rotateArray[i + 1]; } } return 0; } };
Solution 2:
Dichotomy, using cycle, time complexity is O(logn).
Reference source 2:
class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { if (rotateArray.size() == 0) return 0; int index1 = 0; int index2 = rotateArray.size() - 1; int indexmid = 0; while (rotateArray[index1] >= rotateArray[index2]) { if (index2 - index1 == 1) { indexmid = index2; break; } indexmid = (index1 + index2) / 2; if (rotateArray[indexmid] >= rotateArray[index1]) { index1 = indexmid; } else if (rotateArray[indexmid] <= rotateArray[index2]) { index2 = indexmid; } } return rotateArray[indexmid]; } };
Solution 3:
The dichotomy is used to realize recursion, and the time complexity is O (logn).
Refer to source 3:
class Solution { public: int index = 0; int minNumberInRotateArray(vector<int> rotateArray) { if (rotateArray.size() == 0) return 0; minNumberInRotateArrayHelper(rotateArray, 0, rotateArray.size() - 1); return rotateArray[index]; } void minNumberInRotateArrayHelper(vector<int> rotateArray, int left, int right) { if (right - left == 1) { if (rotateArray[left] < rotateArray[right]) index = left; else { index = right; } return; } int mid = (right + left) / 2; if (rotateArray[mid] > rotateArray[right]) { minNumberInRotateArrayHelper(rotateArray, mid, right); } else { minNumberInRotateArrayHelper(rotateArray, left, mid); } } };