189. Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

  • Solution 1. rotate one by one, make a copy of last element, shift all element 1 distance to right, put last element back into the first position, continue k steps.
  • Solution 2. use extra space to save the last k elements from array. move first n-k elements to the right by k steps. copy the extra array back into first k elements.
  • reverse 3 times.
public class Solution {
    public void rotate(int[] nums, int k) {
        int n = nums.length;
        if(n <=1) return; // no need to rotate.
        k = k % n;
        if(k == 0) return;

        swap(nums, 0, n-1);
        swap(nums, 0, k-1);
        swap(nums, k, n-1);


    }

    void swap(int[] nums, int l, int r){
        while(l<r){
            int t = nums[l];
            nums[l] = nums[r];
            nums[r] = t;
            l++;
            r--;
        }
    }
}

results matching ""

    No results matching ""