问题描述:
Rotate an array of n elements to the right by k steps.
示例:
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]
.
问题分析:
将一个数组向右旋转k个步长,可以理解为从右边开始,每一次将最右边的元素移到最左端,一共进行k次操作。
过程详见代码:
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int len = nums.size();
for(int i = 0;i < k; i++)
{
int t = nums.back();
nums.pop_back();
nums.insert(nums.begin(),t);
}
}
};