【发布时间】:2023-03-06 19:14:01
【问题描述】:
我正在尝试编写一个函数,该函数接受一个非负整数,并返回一个非负整数对列表,其值 - 当平方时 - 总和为给定整数。
例子:
5 --> [ [1, 2] ]
25 --> [ [0, 5], [3, 4] ]
325 --> [ [1, 18], [6, 17], [10, 15] ]
我的解决方案在 IDE 中运行,但是当我将其提交给 codewars 时,我收到退出代码错误 139:致命错误:无效的表大小分配失败 - JavaScript 堆内存不足。 codewars 文档表明这是由于算法效率低下造成的。
最初我的解决方案包含一个嵌套循环,这会导致运行时间过长,但我已经重构了我的代码以删除它。尽管降低了复杂性,但我仍然遇到同样的错误。
有什么建议可以进一步降低复杂性吗?
const allSquaredPairs = (n) => {
//get array of all numbers between 0 and sqrt of n
let possibleNums = Array(n)
.fill()
.map((_, i) => {
if ((i + 1) ** 2 <= n) return i + 1; //only numbers lesser than sqrt of n
})
.filter(n => n!=undefined)
possibleNums = [0, ...possibleNums];
const matchingPairs = [];
while (possibleNums.length){
const num1 = possibleNums[0];
const num2 = possibleNums[possibleNums.length-1];
const sum = num1 ** 2 + num2 ** 2
if (sum === n) matchingPairs.push([num1, num2]);
if (sum > n ) possibleNums.pop()
else possibleNums.shift()
}
return matchingPairs;
};
console.log(allSquaredPairs(25));
【问题讨论】:
-
Array(n).map().filter()将您已经很大的数组复制三份。从内存使用的角度来看,这不是有效的。虽然数组的前两个副本将符合垃圾回收条件,但它们将全部三个同时存在,从而增加您的峰值使用量。请正如其他答案已经说过的那样,在数组中预先创建所有可能的值并不是一种有效的方法。
标签: javascript node.js algorithm time-complexity space-complexity