gpt4 book ai didi

javascript - 算法性能 : Solution Analysis of JS Functions

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:04 24 4
gpt4 key购买 nike

<分区>

美好的一天!我对算法性能分析(大 O 时间和空间复杂度)感到不安,想知道我编写的代码是否具有适当的时间和空间复杂度。还有什么方法可以提高复杂度?

下面是两个函数。第一个接受一组数组并运行两个 forEach 数组辅助方法。其目的是正确移动屏幕上的线条。第二个是

函数 1 - 时间复杂度 - O(N^2),空间复杂度 - O(N)...这是正确的吗?

self.penciledLines.forEach((arr, index) => {
arr.forEach((line) => {
if (index === self.selectedArrayLinesIndex) {
if (
line.x1 + xDiff <= 0
|| line.y1 + yDiff <= 0
|| line.x1 + xDiff >= 800
|| line.y1 + yDiff >= 600
|| (line.x2 + xDiff <= 0
|| line.y2 + yDiff <= 0
|| line.x2 + xDiff >= 800
|| line.y2 + yDiff >= 600)
) {
const alerted = localStorage.getItem('alerted') || '';
if (alerted !== 'yes') {
alert("On No! You can't move beyond the drawing canvas");
localStorage.setItem('alerted', 'yes');
}
setTimeout(() => {
localStorage.removeItem('alerted');
}, 1000);
self.mouseIsDown = false;
return;
}
line.move(xDiff, yDiff);
self.pos = [mouseX, mouseY];
}
});
});

函数 2 - 时间复杂度 - O(N^2),空间复杂度 - O(N)...这是正确的吗?时间由另一个 forEach?

中的 forEach 循环决定
let minSquareDistance = null;
let closestIndex = null;

self.lines.forEach((line, index) => {
const squareDistance = line.squareDistanceFrom(x, y);
if (index === 0 || squareDistance < minSquareDistance) {
minSquareDistance = squareDistance;
closestIndex = index;
}
});

let mainArrayIndex; let
subArrayIndex;
self.penciledLines.forEach((arr, mainIndex) => {
arr.forEach((line, subIndex) => {
const squareDistance = line.squareDistanceFrom(x, y);
if (squareDistance < minSquareDistance || minSquareDistance === null) {
minSquareDistance = squareDistance;
// cancel closestIndex
closestIndex = null;
mainArrayIndex = mainIndex;
subArrayIndex = subIndex;
}
});
});

const distanceCheck = minSquareDistance;
if (distanceCheck > 10) {
self.selectedLine = {};
self.selectedArrayLinesIndex = null;
self.selectedArrayLinesToggle = false;
}

感谢您抽出时间,只是想确保我了解如何分析。还有办法改善这种情况吗?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com