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.
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
https://leetcode.com/problems/rotate-array/
https://leetcode.com/discuss/questions/oj/rotate-array?sort=hot
1 public static void rotate(int[] nums, int k) 2 { 3 k=k%nums.length; 4 if(k==0) 5 return; 6 boolean[] flag=new boolean[nums.length]; 7 for(int i=0;i<nums.length;i++) 8 { 9 if(flag[i]) 10 continue; 11 int t1=nums[i]; 12 int t2; 13 for(int j=(i+k)%nums.length;flag[j]==false;j=(j+k)%nums.length) 14 { 15 t2=nums[j]; 16 nums[j]=t1; 17 flag[j]=true; 18 t1=t2; 19 } 20 } 21 }