Javascript method1:188ms;method2:132ms


  • 1
    M

    var rotate = function(nums, k) {

    //below is not in-place modification because slice and concat will create new array
    // var n = nums.length;
    // nums = nums.slice(n - k).concat(nums.slice(0, n-k));
    // console.log(nums);
    
    //method 1: use splice and unshift
    k = k % nums.length;
    var tail = nums.splice(-k,k);
    for (var i = k-1; i >= 0; i--) {
        nums.unshift(tail[i]);
    }
    

    };


  • 1
    M
    //method 2:use apply
    k = k % nums.length;
    var firstHalf = nums.slice(nums.length - k);
    nums.splice(-k, k);
    Array.prototype.unshift.apply(nums, firstHalf);

Log in to reply
 

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