Gyh's Braindump

CN-189. Rotate Array

tags
Rotate

source :

Edge Cases

when nums.length and K has Least Common Multiple

Solution 1 - Change one by one

class Solution {
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        int cur = 0, i = 0;
        while (i < nums.length && cur < nums.length) {
            int start = cur, nextVal = nums[cur];
            do {
                int target = (cur + k) % nums.length;
                int tmp = nums[target];
                nums[target] = nextVal;
                nextVal = tmp;
                cur = target;
                i++;
            } while (cur != start);
            cur = start + 1;
       }
    }
}

Complexity

  • time: O(N)
  • space: O(1)

Solution 2 - Reverse

when done, we actually move last K elements into the start of the array. so we reverse whole array, and reverse (0, k), then reverse (k, nums.length)

class Solution {
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}