Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
向右轮转数组k次。
例如,给定n=7和k=3,那么原数组[1,2,3,4,5,6,7]将会变成[5,6,7,1,2,3,4]
我就说我一开始怎么老错,原来是我看成向左轮转了。。。三种方法的话,直接轮转算一种(就是我写的这个),移动整个数组算一种(虽然每次都要移动整个数组,我不喜欢),截取两个子数组交换大概也算一种。不过其余两个我懒得写了。。。
class Solution {
public:
void rotate(vector<int>& nums, int k) {
for(;k>=nums.size();k-=nums.size());
while(nums.size()-k>0)
{
nums.push_back(nums[0]);
nums.erase(nums.begin());
k++;
}
}
};