Leetcode题解之 —— 旋转数组

思路


题目要求至少写出三种方案

  • 利用popunshift操作(用时263ms)
  • 利用splice(用时106ms)

题解


方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function (nums, k) {
const len = nums.length;
let count = len - 1;

while (count >= len - k) {
nums.unshift(nums.pop());
count--;
}
};

方法二:

1
2
3
4
5
6
7
8
9
10
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function (nums, k) {
const len = nums.length;
const temp = nums.splice(len - k, k);
nums.unshift(...temp);
};