Monday, June 20, 2022

189. Rotate Array

 一刷 06/2022

Version #1 Using Cyclic Replacements

Time O(N)

Space O(1)

Runtime: 3 ms, faster than 23.14% of Java online submissions for Rotate Array.
Memory Usage: 64.6 MB, less than 36.48% of Java online submissions for Rotate Array.

class Solution {

    public void rotate(int[] nums, int k) {

        int len = nums.length;

        if (k % len == 0) {

            return;

        }

        int cnt = 0;

        int startIndex = 0;

        while (cnt < len) {

            int index = startIndex;

            int prev = nums[index];

            do {

                index = (index + k) % len;

                int curr = nums[index];

                nums[index] = prev;

                cnt++;

                prev = curr;

            } while (index != startIndex);

            startIndex++;

        }

    }

}

Version #2 Reversion

Time O(N)

Space O(1)

Runtime: 2 ms, faster than 47.15% of Java online submissions for Rotate Array.
Memory Usage: 64.5 MB, less than 36.48% of Java online submissions for Rotate Array.

class Solution {

    public void rotate(int[] nums, int k) {

        if (k % nums.length == 0) {

            return;

        }

        k %= nums.length;

        reverse(nums, 0, nums.length - 1);

        reverse(nums, 0, k - 1);

        reverse(nums, k, nums.length - 1);

    }

    private void reverse(int[] nums, int start, int end) {

        while (start < end) {

            int temp = nums[start];

            nums[start] = nums[end];

            nums[end] = temp;

            start++;

            end--;

        }

    }

}

No comments:

Post a Comment