牛客题霸 [ 旋转数组的最小数字] C++题解/答案
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
题解:
两种方法:
第一种很简单,直接一遍循环找到最小值,这种方法大家都会
我们介绍第二种二分
二分就像查字典一样,先翻最中间一页,如果目标单词比我们所翻单词大,说明目标单词在右边,反之在左边,假如在右边,我们就进行一样的操作,继续中间翻,然后判断左右
二分答案,就是用二分的方法,在可能的答案区间里找出问题的答案,大多数情况下用于求解满足某种条件下的最大(小)值,前提是答案具有单调性,同时也可以理解为是一种倒推方法(先找答案在判断答案是否可行、有没有更优解)。
代码:
class Solution {
public:int minNumberInRotateArray(vector<int> rotateArray) {int maxn=1e9;for(int i=0;i<rotateArray.size();i++){maxn=min(maxn,rotateArray[i]);}return maxn;}
};
二分法:
class Solution {
public:int minNumberInRotateArray(vector<int> rotateArray) {if(rotateArray.empty())return 0;int low = 0;int hight = rotateArray.size() - 1;int mid = 0;while(low < hight){mid = low + (hight - low)/2;if(rotateArray[mid] >= rotateArray[hight])low =mid +1;elsehight = mid;}return rotateArray[hight];}
};