题目:
Rotate an array ofn elements to the right by ksteps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] isrotated to [5,6,7,1,2,3,4].
Note:Tryto come up as many solutions as you can, there are at least 3 different ways tosolve this problem.
代码:
class Solution {
public:
void rotate(vector<int>& nums, int k) {
vector<int> back_up;
int size=nums.size();
if(k<0)
return;
if(k>size)
k=k%size;
for(int i=k;i>0;i--)
{
back_up.push_back(nums[size-i]);
}
for(int j=size-1;j>=k;j--)
{
nums[j]=nums[j-k];
}
for(int i=0;i<k;i++)
{
nums[i]=back_up[i];
}
return;
}
};
结果: