My 3 ways of rotating array in Java


  • 1
    Z
    public class Solution {
    public void rotate(int[] nums, int k) {
        // solution 0
        // rotate0(nums, k);
        // solution 1
        rotate1(nums, k);
        // solution 2
        // rotate2(nums, k);
    }
    ////////////// solution 2
    public void rotate2(int[] nums, int k) {
        if (nums.length < 2) {
            return;
        }
    
        int kk = k % nums.length;
        if (0 == kk) {
            return;
        }
        
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = nums.length - 1; i >= 0; i--) {
            cache.put((i + kk) % nums.length, nums[i]);
            if (i < kk) {
                nums[i] = cache.get(i);
            } else {
                nums[i] = nums[i - kk];
            }
        }
    }
    ////////////// solution 1
    public void rotate1(int[] nums, int k) {
        if (nums.length < 2) {
            return;
        }
    
        int kk = k % nums.length;
        if (0 == kk) {
            return;
        }
    
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, kk - 1);
        reverse(nums, kk, nums.length - 1);
    }
    
    private void reverse(int[] a, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
            swap(a, i, j);
        }
    }
    private void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
    ////////////// solution 0
    public void rotate0(int[] nums, int k) {
        int kk = k % nums.length;
        if (0 == kk) {
            return;
        }
        
        int[] ext = new int[kk];
        for (int i = nums.length -1; i >= 0; i--) {
            if (i + kk < nums.length) { // swap
                nums[i+kk] = nums[i];
            } else { // copy to new temp array
                ext[i+kk-nums.length] = nums[i];
            }
        }
        
        for (int i = 0; i < ext.length; i++) {
            nums[i] = ext[i];
        }
    }
    }

Log in to reply
 

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