【发布时间】:2021-10-25 11:52:17
【问题描述】:
下面是任务描述和我写函数的两次尝试(都输出错误的结果,例如用这些参数检查我的第二个函数:
sumPairs([10, 5, 2, 3, 7, 5], 10);
*outputs [5, 5], should be [3, 7]*
sumPairs([1, 2, 3, 4, 5, 8, 6, 13, 9], 10);
*outputs [1, 9], should be [2, 8]*
请指出我解决此问题的方式有什么问题。 下面我解释一下我尝试做的事情。
.......................
任务描述:
对的总和。
给定一个整数列表和一个总和值,返回前两个 值(请从左侧解析)按出现的顺序加起来 形成总和。
sum_pairs([11, 3, 7, 5], 10)。
结果:3 + 7 = 10
sum_pairs([4, 3, 2, 3, 4], 6).
结果:4 + 2 = 6,因为最早的索引:0、2,因为整个 对更早。
sum_pairs([0, 0, -2, 3], 2).
结果:未定义。
sum_pairs([10, 5, 2, 3, 7, 5], 10).
结果:3 + 7 = 10,索引:3、4,因为整对更早, 因此是正确答案。
负数和重复数可以并且将会出现。
注意:还将测试长度超过 10,000,000 的列表 元素。确保您的代码不会超时。 ......................................
我的计划是:循环遍历 ints 数组的每个元素,将每个元素添加到 ints 数组的其他元素(除了将相同的元素添加到自身),直到找到 1 或 2 对元素加起来 s总和:*
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (i = 0; i < ints.length; i++) {
for (j = 0; j < ints.length; j++) {
if (j !== i) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
return [ints[i], ints[j]];
}
}
}
}
return undefined;
}
console.log(
sumPairs([10, 5, 2, 3, 7, 5], 10),
// *outputs [5, 5], should be [3, 7]*
sumPairs([1, 2, 3, 4, 5, 8, 6, 13, 9], 10)
// *outputs [1, 9], should be [2, 8]*
)
一旦找到前 1 或 2 对,我就使用 break 语句停止循环。找到 2 对元素后,选择 ints 数组中“较早”(具有较早索引)的对。当然 indexOf 重复的问题再次出现。所以我尝试在每个循环中创建一个单独的计数器。然后将结果推送到单独的 arrResults 中并选择最佳对:
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
let iIndexCount = 0;
let jIndexCount = 0;
for (i = 0; i < ints.length; i++) {
for (j = 0; j < ints.length; j++) {
if (j !== i) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
arrResults.push(ints[i], ints[j], jIndexCount - iIndexCount);
}
}
jIndexCount++;
if (arrResults.length === 9) {
break;
}
}
iIndexCount++;
if (arrResults.length === 9) {
break;
}
}
if (arrResults.length === 9) {
if (arrResults[2] <= arrResults[8]) {
return [arrResults[0], arrResults[1]];
} else {
return [arrResults[6], arrResults[7]];
}
} else if (arrResults.length === 6) {
return [arrResults[0], arrResults[1]];
} else {
return undefined;
}
}
console.log(
sumPairs([10, 5, 2, 3, 7, 5], 10),
// *outputs [5, 5], should be [3, 7]*
sumPairs([1, 2, 3, 4, 5, 8, 6, 13, 9], 10)
// *outputs [1, 9], should be [2, 8]*
)
【问题讨论】:
-
我将您的问题编辑成一组minimal reproducible example 并修正了您的标题。请看一看。它现在可读且可重现
-
yesterday 的问题呢?
标签: javascript arrays for-loop duplicates