javascript - Sum of Pairs,一代码里看不懂的问题。
黄舟
黄舟 2017-04-11 11:38:40
[JavaScript讨论组]

因为所有问题都已经在截图里,所以就不另外说了。

这个题目我想了一天都没想出来,后来有个群的朋友告诉我这个方法。这个代码也是他写好的,我大致弄懂了思路,但还是想不明白为什么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

感谢回答。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(1)
怪我咯
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]了
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号