Rotate Array - Javacript

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.

[show hint]

Related problem: Reverse Words in a String II

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Tags

Array

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

* push(elem0, elem1, elem2, …) 向数组的末尾添加元素,并返回新的长度
* 
* pop() 删除数组中最后的一个元素,同时返回该元素
* 
* shift() 把数组的第一个元素从其中删除,并返回第一个元素的值
* 
* unshift(elem0, elem1, elem2, …) 向数组的开头添加一个或更多元素,并返回新的长度
* 
* splice(start, len, elem0, elem1, elem2, …) 从数组的start位置删除len个元素,
* 同时在该位置填充elem0, elem1等元素。如果elem为空,则直接进行删除,同时返回被删除的元素(array)
* 
* slice(start, len) 从数组的start位置删除len个元素,同时返回被删除的元素,而原数组不变
* 
* concat(array) 在数组的后面接上一个数组array,同时返回拼接完成的数组,而原数组不变
* 
* 
从上面的各个方法中,我们能够看到,只能使用前面5个方法,最后2个方法不能修改原数组。
因此现在的思路为:使用splice()得到最后的k个元素,然后使用unshift()把得到的数据一个个填充到数组的前面

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function (nums, k) {

    // Pay attention to k, k might be larger than the lengths
    k = k % nums.length;

    // get the last k digits of nums
    var tmp = nums.splice(-k, k);
    for (var i = k - 1; i >= 0; i--) {
        nums.unshift(tmp[i]);
    }
};

Solution 2
// Reverse the array from 0 ~ k
// Reverse the array from k ~ len
// Reverse the array from 0 ~ len

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    var len = nums.length;
    k = k%len;
    
    reverse(nums, 0, len-k-1);
    reverse(nums, len-k, len-1);
    reverse(nums, 0, len-1);
};

function reverse(num, start, end) {
    if(num.length<=1) {
        return;
    }
    
    while(start < end) {
        var temp = num[start];
        num[start] = num[end];
        num[end] = temp;
        start++;
        end--;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值