未完成--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;
}
目录
相关文章
|
3月前
|
网络协议 算法 Java
记录一道算法题-split和Integer.parseInt()
记录一道算法题-split和Integer.parseInt()
38 0
LeetCode 307. Range Sum Query - Mutable
update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
91 0
LeetCode 307. Range Sum Query - Mutable
LeetCode 304. Range Sum Query 2D - Immutable
给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。
90 0
LeetCode 304. Range Sum Query 2D - Immutable
|
索引
LeetCode 303. Range Sum Query - Immutable
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
80 0
LeetCode 303. Range Sum Query - Immutable
|
人工智能 索引
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero
LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero
|
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)
428 0
修改sequenc number
create or replace procedure CHANGE_SEQ_NUMBER( PI_SEQ_OWNER VARCHAR2 , PI_SEQNAME VARCHAR2 , PI_LAST_NUMBER NUMBER) IS V_LastValue integer; V_incr...
663 0
1093. Count PAT's (25)
#include #include #include using namespace std; int main() { string s; cin >> s; long long sum = 0, p = 0, t = 0; for (int i = 0; i < s.
792 0