189. Rotate Array
方法一/二:
注意的是k有可能是invalid,要对数组的长度取余
1. 新建一个同长度的数组,把nums前n-k个元素拷到newArr中的后n-k个里
2.把nums后k个元素拷到newArr中的前k个中
1 public void rotate(int[] nums, int k) { 2 if(nums.length == 0) { 3 return; 4 } 5 int len = nums.length; 6 k = k % len; 7 reverse(nums, 0, len - 1); 8 reverse(nums, 0, k - 1); 9 reverse(nums, k, len - 1); 10 } 11 12 private void reverse(int[] nums, int start, int end) { 13 while(start < end) { 14 int temp = nums[start]; 15 nums[start] = nums[end]; 16 nums[end] = temp; 17 start++; 18 end--; 19 } 20 }
3.把newArr整个全部拷贝回nums
1 public void rotate(int[] nums, int k) { 2 if(nums.length == 0) { 3 return; 4 } 5 int len = nums.length; 6 k = k % len; 7 int[] lastK = new int[len]; 8 for(int i = 0; i < k; i++) { 9 lastK[i] = nums[nums.length - k + i]; 10 } 11 for(int i = 0; i < nums.length - k; i++) { 12 lastK[i + k] = nums[i]; 13 } 14 for(int i = 0; i < len; i++) { 15 nums[i] = lastK[i]; 16 } 17 }
使用System.copyarray(source, sourcePos, des, dexPos, len);
1 public void rotate(int[] nums, int k) { 2 if(nums.length == 0) { 3 return; 4 } 5 int n = nums.length; 6 k = k % n; 7 int[] newN = new int[n]; 8 System.arraycopy(nums, 0, newN, k, n - k); 9 System.arraycopy(nums, n - k, newN, 0, k); 10 System.arraycopy(newN, 0, nums, 0, n); 11 }
方法三:
1.把nums整个倒过来
2.把前k个倒过来
3.把后n-k个倒过来