BM21. 旋转数组的最小数字
描述
有一个长度为 n 的非降序数组,比如[1,2,3,4,5],将它进行旋转,即把一个数组最开始的若干个元素搬到数组的末尾,变成一个旋转数组,比如变成了[3,4,5,1,2],或者[4,5,1,2,3]这样的。请问,给定这样一个旋转数组,求数组中的最小值。示例1
输入:
[3,4,5,1,2]
输出:
1
示例2
输入:
[3,100,200,3]
输出:
3
C++ 解法, 执行用时: 4ms, 内存消耗: 532KB, 提交时间: 2022-04-17
class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { if(rotateArray.size() == 0){ return 0; } int left = 0; int right = rotateArray.size()-1; while(left<right){ if(rotateArray[left]<rotateArray[right]){ return rotateArray[left]; } int mid = left + (right-left)/2; if(rotateArray[mid]>rotateArray[right]){ left = mid + 1; } else if(rotateArray[mid]<rotateArray[right]){ right = mid; } else{ right--; } } return rotateArray[left]; } };
C++ 解法, 执行用时: 4ms, 内存消耗: 544KB, 提交时间: 2022-06-15
class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { int left=0, right=rotateArray.size()-1; while(left<right) { int mid=(left+right)/2; if(rotateArray[mid]>rotateArray[right]) left=mid+1; else if(rotateArray[mid]<rotateArray[right]) right=mid; else right--; } return rotateArray[left]; } };
C++ 解法, 执行用时: 4ms, 内存消耗: 544KB, 提交时间: 2022-04-04
class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { int n=rotateArray.size(); if(n==1)return rotateArray[0]; int i=0,j=n-1; while(i<=j){ if(i==j)return rotateArray[i]; int mid=(i+j)/2; if(rotateArray[mid]>rotateArray[j]){ i=mid+1; } else{ if(rotateArray[mid]==rotateArray[j]){ j--; } else j=mid; } } return 0; } };
C++ 解法, 执行用时: 4ms, 内存消耗: 544KB, 提交时间: 2021-09-13
class Solution { public: int minNumberInRotateArray(vector<int> rotateArray) { int left = 0, right = rotateArray.size() - 1; while(left < right) { int mid = left + (right - left) / 2; if(rotateArray[mid] > rotateArray[right]) left = mid + 1; else if(rotateArray[mid] < rotateArray[right]) right = mid; else --right; } return rotateArray[right]; } };
C++ 解法, 执行用时: 4ms, 内存消耗: 544KB, 提交时间: 2021-09-09
class Solution { public: int minNumberInRotateArray(vector<int> a) { int n = a.size(); n--; while (a[0] == a[n]) n--; if (a[0] < a[n]) return a[0]; int l = 0, r = n; while (l < r) { int mid = l + r >> 1; if (a[mid] < a[0]) r = mid; else l = mid + 1; } return a[r]; } };