Solution using int[k] storage array


  • 0
    N
    public void Rotate(int[] nums, int k)
    {
        if (nums == null || nums.Length <= 1) { return; }
    
        int len = nums.Length;
        k %= len;
        if (k == 0) { return; }
    
        // grab last k elements
        int[] storage = new int[k];
        for (int i = len - k, j = 0; i < len; i++, j++)
        {
            storage[j] = nums[i];
        }
    
        // shift the elemnts by k 
        for (int i = len - 1; i >= k; i--)
        {
            nums[i] = nums[i - k];
        }
    
        // add back last k elements
        for(int i = 0; i < k; i++)
        {
            nums[i] = storage[i];
        }
    }

Log in to reply
 

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