LeetCode 189.Rotate Array

問題描述:數組

189.Rotate Arrayapp

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

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].code

解題思路:element

  1. 使用數組自帶的pop()方法和unshift()方法把數組最後一個取出來加入到頭部。it

  2. 使用數組的slice()方法獲得後k個數,再用splice()方法刪去後k個數,最後用unshift方法把獲得的後k個數添加到數組前面。io

代碼1:function

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

    for (i = 0; i < k; i++) {
        nums.unshift(nums.pop());
    }

};

代碼2:方法

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    let len = nums.length;
    k = k%len;
    let nums1 = nums.slice(len - k);
    nums.splice(-k, k);
    Array.prototype.unshift.apply(nums, nums1);
};
相關文章
相關標籤/搜索