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.
注意:k可能大于n
Approach #1
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n=nums.size();
vector<int> tmp(nums);//void
int j=0;
for(int i=0;i<n;i++)
{
nums[(i+k)%n]=tmp[i];//移动数据
}
}
};
时间复杂度: O(n)
空间复杂度:O(n)
Approach #2
每次把最后一个数据往前复制,其他数据往后挪,重复k次