题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
利用两个index, 将复杂度降至O(logn), 注意考虑一种特殊情况要使用遍历查找
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include<stack>
#include<cmath>
#include<algorithm>
#include <iomanip>
using namespace std;
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
if(rotateArray.size()==0) {
return 0;
} else if(rotateArray.size()==1) {
return rotateArray[0];
}
int index1=0,index2=rotateArray.size()-1;
while(index1!=index2-1) {
int mid=(index1+index2)/2;
if(rotateArray[mid]==rotateArray[index1]&&rotateArray[index1]==rotateArray[index2]) {
int min=rotateArray[0];
for(int i=0;i<rotateArray.size();i++) {
if(rotateArray[i]<min) {
min=rotateArray[i];
}
}
return min;
} else if(rotateArray[mid]>=rotateArray[index1]) {
index1=mid;
} else if(rotateArray[mid]<=rotateArray[index2]) {
index2=mid;
}
}
return rotateArray[index2];
}
};
int main()
{
Solution sol;
vector<int> test={3,4,5,1,1,2,3};
int res=sol.minNumberInRotateArray(test);
cout<<res<<endl;
system("pause");
return 0;
}