LeetCode – Rotate Array

Solution 1 (in place):

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    while(k > 0)
    {
        for (var i = 0; i < nums.length; i++)
        {
            var previousElement;
            var tmp = nums[i];

            if (i === 0)
                nums[i] = nums[nums.length - 1];
            else
                nums[i] = previousElement;

            previousElement = tmp;
        }
        k--;
    }

    return nums;
};

Leave a Reply

Your email address will not be published. Required fields are marked *