Rotate an array of n elements to the right by K steps.
For example, with n = 7 and k = 3, the array is [1,2,3,4,5,6,7] rotated to [5,6,7,1,2,3,4] .
Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem. [Show hint]
Hint:could do it in-place with O (1) extra space?
Related Problem:reverse Words in a String II
Solution 1:reverse[1,2,3,4]=[4,3,2,1], reverse[5,6,7]=[7,6,5], reverse[4,3,2,1,7,6,5]=[5,6,7,1,2,3,4]
1#include <algorithm>2 classSolution {3 Public:4 voidRotate (vector<int>& Nums,intK) {//runtime:24ms5 intn=nums.size ();6K%=N;7Reverse (Nums.begin (), Nums.begin () +n-k);8Reverse (Nums.begin () +n-k,nums.end ());9 Reverse (Nums.begin (), Nums.end ());Ten } One};
Solution 2: Timeout
1 classSolution {2 Public:3 voidRotate (vector<int>& Nums,intk) {4 intn=nums.size ();5K%=N;6 while(k--){7 inttemp=nums[n-1];8 for(inti=n-1;i>0; i--){9nums[i]=nums[i-1];Ten } Onenums[0]=temp; A } - } -};
Solution 3:
1 voidRotateintNums[],intNintk) {2K = k%N; 3 if(k = =0)return; 4 int*temp =New int[n]; 5memcpy (temp, nums+ (n-k),sizeof(int)*k); 6memcpy (Temp+k, Nums,sizeof(int) * (nk)); 7memcpy (Nums, temp,sizeof(int)*N); 8 Delete[] temp; 9}
"Leetcode" 189-rotate Array