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:
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.
思路:
题目要求是在一个数组中向右移动k步,求得最后的数组的结果.首先对这个k steps如果移动的是数组size的 倍数的话,整体效果是数组看到并没有被移动。因此,k%nums.szie()计为实际的移动步数。将数组分成两部分,两部分各自reverse以后再整体reverse一下就可以了
注意在使用reverse这个函数的时候,reverse的第一个参数是操作的起始位置,第二个位置是结束位置的下一个元素。
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int size=nums.size();
k%=size;
if(k==0) //当K大于数组的size的时候直接返回,这个时候数组的数字的分布不会被改变
return ;
reverse(nums.begin(),nums.begin()+size-k); //not <span style="font-family: Arial, Helvetica, sans-serif;">nums.begin()+size-k-1</span>
reverse(nums.begin()+size-k,nums.end());
reverse(nums.begin(),nums.end());
}
};