未完成--Sum of Pairs

简介: 未完成--Sum of Pairs
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]
Negative numbers and duplicate numbers can and will appear.
NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out.

代码

var sum_pairs = function (ints, s) {
    for (var i = 0, l = ints.length, r = []; i < l; i++) {
        for (var j = 1; j < l; j++) {
            if (ints[i] + ints[j] == s) {
                if (r[1]==null||j + i >= r[0] + r[1]) {
                    r[0] = i;
                    r[1] = j;
                }
            }
        }
    }
    return r[0]?[ints[r[0]], ints[r[1]]]:"undefined for sum = " + s;
}
目录
相关文章
|
6月前
|
索引 Python
pd.concat([pre_salers,new_salers],keys=['pre','new'],axis=0)啥意思
pd.concat([pre_salers,new_salers],keys=['pre','new'],axis=0)啥意思
|
6月前
|
索引 Python
pd.concat([pre_salers,new_salers],keys=['pre','new'],axis=0)啥意思
pd.concat([pre_salers,new_salers],keys=['pre','new'],axis=0)啥意思
|
数据可视化 数据处理
解决 FAILED: UDFArgumentException explode() takes an array or a map as a parameter 并理解炸裂函数和侧视图
解决 FAILED: UDFArgumentException explode() takes an array or a map as a parameter 并理解炸裂函数和侧视图
120 0
|
索引
LeetCode 416. Partition Equal Subset Sum
给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
120 0
LeetCode 416. Partition Equal Subset Sum
|
人工智能 索引
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
CF1454 E. Number of Simple Paths (基环树 拓扑排序)
CF1454 E. Number of Simple Paths (基环树 拓扑排序)
100 0
|
存储 索引
成功解决ValueError: If using all scalar values, you must pass an index
成功解决ValueError: If using all scalar values, you must pass an index
【1144】The Missing Number (20 分)
【1144】The Missing Number (20 分) 【1144】The Missing Number (20 分)
81 0
|
SQL Java 数据库
PreparedStatement 模糊匹配 结果却:Parameter index out of range (1 > number of parameters, which is 0)
PreparedStatement 模糊匹配 结果却:Parameter index out of range (1 > number of parameters, which is 0)
513 0