题目
定义一个函数,实现数组的旋转。如输入 [1, 2, 3, 4, 5, 6, 7] 和 key = 3, 输出 [5, 6, 7, 1, 2, 3, 4]
第一种解法
- 将
k后面的所有元素拿出来作为part1 - 将
k前面的所有元素拿出来作为part2 - 返回
part1.concat(part2)
function rotate(arr, k) {
const len = arr.length;
if (!k || len === 0) return arr;
const step = Math.abs(k % len);
const part1 = arr.slice(-step);
const part2 = arr.slice(0, len - step);
const part3 = part1.concat(part2);
return part3;
}
第二种解法
- 将
k后面的元素,挨个pop然后unshift到数组前面
function rotate2(arr, k) {
const length = arr.length;
if (!k || length === 0) return arr;
const step = Math.abs(k % length);
for (let i = 0; i < step; i++) {
const n = arr.pop();
if (n != null) {
arr.unshift(n);
}
}
return arr;
}
功能测试
const arr = [1, 2, 3, 4, 5, 6, 7];
const a1 = rotate(arr, 80);
console.log("a1 :>> ", a1);
// a1 :>> [
// 5, 6, 7, 1,
// 2, 3, 4
// ]
const a2 = rotate2(arr, 80);
console.log("a2 :>> ", a2);
// a2 :>> [
// 5, 6, 7, 1,
// 2, 3, 4
// ]
性能测试
const arr1 = [];
for (let i = 0; i < 10 * 10000; i++) {
arr1.push(i);
}
console.time("rotate1");
rotate(arr1, 9 * 10000);
console.timeEnd("rotate1"); // 885ms O(n^2)
const arr2 = [];
for (let i = 0; i < 10 * 10000; i++) {
arr2.push(i);
}
console.time("rotate2");
rotate2(arr2, 9 * 10000);
console.timeEnd("rotate2"); // 1ms O(1) unshift性能很差
文章介绍了两种在JavaScript中实现数组旋转的方法,一种是通过切片和concat操作,另一种是使用pop和unshift。对这两种方法进行了功能测试和性能测试,显示了在大规模数据时,使用切片和concat的方法性能较差,而pop和unshift的方法具有更好的时间复杂度。
265

被折叠的 条评论
为什么被折叠?



