资讯专栏INFORMATION COLUMN

LeetCode 189.Rotate Array

leanote / 2214人阅读

摘要:问题描述解题思路使用数组自带的方法和方法把数组最后一个取出来加入到头部。使用数组的方法得到后个数,再用方法删去后个数,最后用方法把得到的后个数添加到数组前面。

问题描述:

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

解题思路:

使用数组自带的pop()方法和unshift()方法把数组最后一个取出来加入到头部。

使用数组的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);
};

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/88141.html

相关文章

  • LeetCode 189: Rotate Array (Java)

    摘要:解法一假设数组为先把换到的位置,把拿着换到的位置,把拿着换到的位置。。。停止条件姑且假设为当置换的数回到数组的首位。不过换一个栗子上述方法就不通了,比如数组为换一轮发现结果是。 题目: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [...

    Airmusic 评论0 收藏0
  • leetcode部分题目答案之JavaScript版

    摘要:自己没事刷的一些的题目,若有更好的解法,希望能够一起探讨项目地址 自己没事刷的一些LeetCode的题目,若有更好的解法,希望能够一起探讨 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...

    alphahans 评论0 收藏0
  • [LeetCode] 702. Search in a Sorted Array of Unknow

    Problem Given an integer array sorted in ascending order, write a function to search target in nums. If target exists, then return its index, otherwise return -1. However, the array size is unknown t...

    zlyBear 评论0 收藏0
  • leetcode-78-Subsets

    摘要:描述解释就是普通的动态规划吧,找准规律,所有数字过一遍,每个数字都有添加和不被添加两种情况,所有情况的综合 描述 Given a set of distinct integers, nums, return all possible subsets(the power set). Note: The solution set must not contain duplicate sub...

    dockerclub 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<