leetcode 189

时间:2024-12-20 12:33:20

189. Rotate Array

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].

将数组向右旋转k位。

代码如下:

 class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k = k%n;
if(k){
vector<int> p,q;
for(int i=n-k;i<n;i++){
p.push_back(nums[i]);
}
for(int i=;i<n-k;i++){
q.push_back(nums[i]);
}
for(int i=;i<k;i++){
nums[i]=p[i];
}
for(int i=k;i<n;i++){
nums[i]=q[i-k];
}
}
}
};