【leetcode初级算法JS实现】3.旋转数组
程序员文章站
2022-03-08 07:57:31
...
// 解法1
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
for(let i = 0; i < k; i++){
let temp = nums.pop();
nums.unshift(temp);
}
};
// 解法2
// splice(start, num)
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
let length = nums.length;
nums.unshift(...nums.splice(length - k, k));
};