zl程序教程

您现在的位置是:首页 >  其它

当前栏目

[Algorithm] 189. Rotate Array

Array ALGORITHM rotate
2023-09-14 08:59:14 时间

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Solution 1:

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

};

Solution 2:

var rotate = function(nums, k) {
    var a = [];
    for (var i = 0; i < nums.length; i++) {
        a[(i+k)%nums.length] = nums[i];
    }
    for (var j = 0; j < nums.length; j++) {
        nums[j] = a[j]
    }
};

Solution 3:

var rotate = function(nums, k) {
    k = k % nums.length;
    nums.unshift(...nums.splice(nums.length - k))
};