189. Rotate Array java solutions
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.
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
1 public class Solution { 2 public void rotate(int[] nums, int k) { 3 int[] tmp = new int[k]; 4 int len = nums.length; 5 k %= len;//处理k大于数组长度的情况 6 for(int i = 0; i < k; i++){ 7 tmp[i] = nums[len-k+i]; 8 } 9 len--; 10 for(int i = len-k; i>= 0; i--){ 11 nums[len--] = nums[i]; 12 } 13 for(int i = 0; i < k; i++){ 14 nums[i] = tmp[i]; 15 } 16 } 17 }
解法二将数组0~len-1 逆置一次,0~k-1逆置一次,k~len-1逆置一次,即可得答案:
1 public class Solution { 2 public void rotate(int[] nums, int k) { 3 int len = nums.length; 4 k %= len; 5 reverse(nums,0,len-1); 6 reverse(nums,0,k-1); 7 reverse(nums,k,len-1); 8 } 9 10 public void reverse(int[] nums,int s, int e){ 11 while(s <= e){ 12 int tmp = nums[s]; 13 nums[s] = nums[e]; 14 nums[e] = tmp; 15 s++; 16 e--; 17 } 18 } 19 }