题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
解体思路:旋转数组就是将数组最开始的n个数值依次追加到数组的末尾,所以非递减旋转数组是由两部分有序的子数组组成,所以该数组的最小值肯定是两个子数组的连接处,所以从后面开始遍历比较,后一个数小于前一个数,那这个数就肯定是数组中的最小值了。
具体代码:
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
if(rotateArray.size()==0)
return 0;
for(int i=rotateArray.size()-1;i>=0;i--)
{
if(rotateArray[i]<rotateArray[i-1])
return rotateArray[i];
}
}
};
题目扩展:如何实现数组的旋转
问题分析:创建一个临时数组,将前几个数存入临时数组,然后数组内其余数前移,最后将临时数组中的数追加到原数组中
具体代码:
class Solution {
public:
void RotateArray(vector<int> rotateArray,int k) {
vector<int> rotateArray_temp;
for(int i=0;i<k;i++)//将前k个值存入临时数组中
rotateArray_temp[i]=rotateArray[i];
for(;i<rotateArray.size();i++)//将其余值前移k个单位
rotateArray[i-k]=rotateArray[i];
for(int j=0,i=rotateArray.size()-K;j<rotateArray_temp.size();i++,j++)//
rotateArray[i]=rotateArray_temp[j];
}
return rotateArray;
};