数组 - 旋转数组

题目

https://leetcode-cn.com/problems/rotate-array/

个人解法

测试用例数(个) 执行用时(ms) 战胜
34 116 70.10%
/**
 * @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;
    var originNums = {};
    
    for (var i = 0 ; i < len ; i++) {
        var num = originNums[i] !== undefined
            ? originNums[i]
            : nums[i];

        var nextIndex = (i + k) % len;

        originNums[nextIndex] = nums[nextIndex];
        nums[nextIndex] = num;
    }
    
    return nums;
};

最快解法

测试用例数(个) 执行用时(ms) 战胜
34 64 100%
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function(nums, k) {
    let l = nums.length;
    k %= l
    nums.unshift(...nums.splice(nums.length - k, k))
};

分析

此题的关键点如下:

个人解决:

着眼点还是局限在单个元素的旋转上。

最快解决:

将部分作为整体前置,实现整体旋转。视野更高。
*****
Written by Zheng Yu on 26 March 2019