Fast solution by array copy


  • 0
    X
    public void rotate(int[] nums, int k) {
        final int len = nums.length;
        k = k % len;
        if (k == 0) return;
        if (k < 0) k = len + k;
        if (k < len - k) {
            int[] tmp = Arrays.copyOfRange(nums, len - k, len);
            System.arraycopy(nums, 0, nums, k, len - k);
            System.arraycopy(tmp, 0, nums, 0, k);
        } else {
            int[] tmp = Arrays.copyOfRange(nums, 0, len - k);
            System.arraycopy(nums, len - k, nums, 0, k);
            System.arraycopy(tmp, 0, nums, k, len - k);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.