Sum of Pairs 的优化解决方案:Codewars
Optimizing solution of Sum of Pairs: Codewars
我需要帮助优化问题的解决方案,我已经解决了问题,但我的代码不足以处理大型数组 -
codeWars : Sum of Pairs - problem
这是我的代码 -
var sum_pairs=function(e, sum){
var result=null;
var arrLen=e.length;
for(let i=0;i<arrLen-1;i++){
let nextIndex=e.slice(i+1,arrLen).indexOf(sum-e[i]);
if(nextIndex>=0){
result=[e[i],e[nextIndex+1+i]];
arrLen=nextIndex+1+i;
}
}
return result;
}
好吧,我知道这不是一个好的解决方案。无论如何,这通过了所有测试用例,但在遇到大数组时失败了 -
Result On codewars
我想知道如何优化这段代码,也想学习写出好的代码的技巧。
一种解决方案是使用 Set
数据结构来记住所有准备好迭代的数字。然后我们可以检查每个元素是否有一个总和为 s
的数字。该集合具有用于插入和搜索的平均恒定时间复杂度,使算法在时间上呈线性(并且 space)。
var sum_pairs=function(ints, s){
if (ints.length < 2) return undefined; //not enough numbers for pair.
let intSet = new Set()
intSet.add(ints[0]);
for (let i=1; i < ints.length; ++i){
let needed = s-ints[i];
if (intSet.has(needed)){//check if we have already seen the number needed to complete the pair.
return [needed,ints[i]];
}
intSet.add(ints[i]);//if not insert the number in set and continue.
}
return undefined;//No answer found
}
我需要帮助优化问题的解决方案,我已经解决了问题,但我的代码不足以处理大型数组 - codeWars : Sum of Pairs - problem
这是我的代码 -
var sum_pairs=function(e, sum){
var result=null;
var arrLen=e.length;
for(let i=0;i<arrLen-1;i++){
let nextIndex=e.slice(i+1,arrLen).indexOf(sum-e[i]);
if(nextIndex>=0){
result=[e[i],e[nextIndex+1+i]];
arrLen=nextIndex+1+i;
}
}
return result;
}
好吧,我知道这不是一个好的解决方案。无论如何,这通过了所有测试用例,但在遇到大数组时失败了 - Result On codewars
我想知道如何优化这段代码,也想学习写出好的代码的技巧。
一种解决方案是使用 Set
数据结构来记住所有准备好迭代的数字。然后我们可以检查每个元素是否有一个总和为 s
的数字。该集合具有用于插入和搜索的平均恒定时间复杂度,使算法在时间上呈线性(并且 space)。
var sum_pairs=function(ints, s){
if (ints.length < 2) return undefined; //not enough numbers for pair.
let intSet = new Set()
intSet.add(ints[0]);
for (let i=1; i < ints.length; ++i){
let needed = s-ints[i];
if (intSet.has(needed)){//check if we have already seen the number needed to complete the pair.
return [needed,ints[i]];
}
intSet.add(ints[i]);//if not insert the number in set and continue.
}
return undefined;//No answer found
}