LeetCode 189.Rotate Array

题目形貌:

189.Rotate Array

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

解题思绪:

  1. 运用数组自带的pop()要领和unshift()要领把数组末了一个取出来加入到头部。

  2. 运用数组的slice()要领获得后k个数,再用splice()要领删去后k个数,末了用unshift要领把获得的后k个数添加到数组前面。

代码1:

/**
 * @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);
};
    原文作者:puhongru
    原文地址: https://segmentfault.com/a/1190000008477780
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞