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位。
代码如下:
1 class Solution { 2 public: 3 void rotate(vector<int>& nums, int k) { 4 int n = nums.size(); 5 k = k%n; 6 if(k){ 7 vector<int> p,q; 8 for(int i=n-k;i<n;i++){ 9 p.push_back(nums[i]); 10 } 11 for(int i=0;i<n-k;i++){ 12 q.push_back(nums[i]); 13 } 14 for(int i=0;i<k;i++){ 15 nums[i]=p[i]; 16 } 17 for(int i=k;i<n;i++){ 18 nums[i]=q[i-k]; 19 } 20 } 21 } 22 };