我在 CodeWars 上找到了一个任务,我设法解决了它,但是,提交后说:
Execution timed out: (12000 ms)
当我尝试测试该功能是否通过时,但我猜它太慢了。
在你谴责我没有自己找到答案之前。我真的不关心提交它作为回复,但我不知道如何让它更快,这就是我在这里的原因。
这是功能:
const ls = [0, 1, 3, 6, 10]
const partsSums = (ls) => {
const sum = []
for(let i = 0, len = ls.length; i < len + 1; i++) {
let result = ls.slice(i).reduce( (accumulator, currentValue) => accumulator + currentValue, 0)
sum.push(result)
}
return sum
}
以下是说明:Let us consider this example (array written in general format):
ls = [0, 1, 3, 6, 10]
Its following parts:
ls = [0, 1, 3, 6, 10] ls = [1, 3, 6, 10] ls = [3, 6, 10] ls = [6, 10] ls = [10] ls = []
The corresponding sums are (put together in a list): [20, 20, 19, 16, 10, 0]
The function parts_sums (or its variants in other languages) will take as parameter a list ls and return a list of the sums of its parts as defined above.
最佳答案
对于这种数组操作,最好不要使用内置方法,如 slice
或 reduce
,因为它们比 for
慢循环,或任何其他循环方法。
这种方法采用单循环并使用索引来获取给定数组的值并获取新数组的最后一个总和。
对 Codewars: Sums of Parts 的一些速度测试:
sum = []; sum[i] = 0;
(这个答案的第一个版本),Array(i + 1).fill(0)
并且没有 sum[i] = 0;
, Array(i + 1)
和 sum[i] = 0;
(见下文),const
partsSums = (ls) => {
let i = ls.length;
const sum = Array(i + 1);
sum[i] = 0;
while (i--) sum[i] = sum[i + 1] + ls[i];
return sum;
},
ls = [0, 1, 3, 6, 10];
console.log(...partsSums(ls));
关于javascript - 提高 JavaScript 函数的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63241719/