javascript - Sum of Pairs,一代码里看不懂的问题。
本文介绍了javascript - Sum of Pairs,一代码里看不懂的问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
因为所有问题都已经在截图里,所以就不另外说了。
这个题目我想了一天都没想出来,后来有个群的朋友告诉我这个方法。这个代码也是他写好的,我大致弄懂了思路,但还是想不明白为什么return的数组,不是ints[i]在前面。我试过了,如果把return的数组两个元素对调,就无法通过检测。
图片不够清晰,还是把详情写一下吧。
题目大意:
Sum of Pairs
Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
示例:
sum_pairs([11, 3, 7, 5], 10)
# ^--^ 3 + 7 = 10
== [3, 7]
sum_pairs([4, 3, 2, 3, 4], 6)
# ^-----^ 4 + 2 = 6, indices: 0, 2 *
# ^-----^ 3 + 3 = 6, indices: 1, 3
# ^-----^ 2 + 4 = 6, indices: 2, 4
# * entire pair is earlier, and therefore is the correct answer
== [4, 2]
sum_pairs([0, 0, -2, 3], 2)
# there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)
sum_pairs([10, 5, 2, 3, 7, 5], 10)
# ^-----------^ 5 + 5 = 10, indices: 1, 5
# ^--^ 3 + 7 = 10, indices: 3, 4 *
# * entire pair is earlier, and therefore is the correct answer
== [3, 7]
我提交的代码:
var sum_pairs=function(ints, s){
//your code here
var set=new Set();
for(var i=0;i<ints.length;i++){
if(set.has(s-ints[i])){
return [s-ints[i],ints[i]]; //**此处不明白为什么不是ints[i]在前面。**
}
set.add(ints[i]);
}
return undefined;
}
感谢回答。
解决方案
sum_pairs([10, 5, 2, 3, 7, 5], 10)
就上面这一个来说,当ints[i]为7的时候,s-int[i]=3存在,所以输出
[s-int[i],int[i]]=[3,7]
如果int[i]在前不就成了[7,3]了
这篇关于javascript - Sum of Pairs,一代码里看不懂的问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文