|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * Rotate an array of n elements to the right by k steps |
| 5 | + * For example, with n = 7 and k = 3, |
| 6 | + * the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. |
| 7 | + * |
| 8 | + * Note: |
| 9 | + * Try to come up as many solutions as you can, there are at least 3 different |
| 10 | + * ways to solve this problem. |
| 11 | + * |
| 12 | + * Hint: |
| 13 | + * Could you do it in-place with O(1) extra space? |
| 14 | + * |
| 15 | + * Related problem: |
| 16 | + * Reverse Words in a String II |
| 17 | + * |
| 18 | + * Tags: Array |
| 19 | + */ |
| 20 | +class RotateArray { |
| 21 | + public static void main(String[] args) { |
| 22 | + RotateArray r = new RotateArray(); |
| 23 | + // int[] nums = { 1, 2, 3, 4, 5, 6, 7 }; |
| 24 | + // int k = 3; |
| 25 | + // r.rotate(nums, k); |
| 26 | + // System.out.println(Arrays.toString(nums)); |
| 27 | + // |
| 28 | + // int[] nums2 = { 1, 2, 3, 4, 5, 6 }; |
| 29 | + // int k2 = 2; |
| 30 | + // r.rotate(nums2, k2); |
| 31 | + // System.out.println(Arrays.toString(nums2)); |
| 32 | + |
| 33 | + int[] nums3 = { 1, 2 }; |
| 34 | + int k3 = 2; |
| 35 | + r.rotate(nums3, k3); |
| 36 | + System.out.println(Arrays.toString(nums3)); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * O(n) Time, O(1) Space |
| 41 | + * Build a full circle of rotation |
| 42 | + * Start from current index and repeat exactly "length of array" times |
| 43 | + * 1. Calculate new index which is current index move k steps forward |
| 44 | + * If move out of range, just start from beginning again |
| 45 | + * newIdx = (curIdx + k ) % len |
| 46 | + * 2. Circle can be the same, for example, n = 6, k = 2 |
| 47 | + * Index will be 0, 2, 4, 0, 2, 4 |
| 48 | + * So save the start index of the circle |
| 49 | + * If start from there again, move one step forward |
| 50 | + */ |
| 51 | + public void rotate(int[] nums, int k) { |
| 52 | + if (nums == null || nums.length == 0) return; |
| 53 | + if (nums.length == 1 || k == 0 || k == nums.length) return; // special cases |
| 54 | + |
| 55 | + int len = nums.length; |
| 56 | + k %= len; |
| 57 | + int idx = 0; |
| 58 | + int tmp = nums[idx]; // the number to write to new index |
| 59 | + int tmp2; // save the number at new index |
| 60 | + for (int i = 0, j = 0; i < len; i++) { // j is the start index of current circle |
| 61 | + idx = (idx + k) % len; |
| 62 | + tmp2 = nums[idx]; |
| 63 | + nums[idx] = tmp; |
| 64 | + tmp = tmp2; |
| 65 | + if (idx == j) { // circle ends |
| 66 | + idx = ++j; // move to next circle |
| 67 | + tmp = nums[idx]; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments