JS for循环中的for循环,我猜是作用域问题
输入是数组INTS[11,2,7,8,4,6]和整数s 10,函数是输出一个数组,数组中的两个数字来自整型数,这两个数的和首先是10。所以这里的输出应该是[2,8],因为2+8=10。为什么它输出空数组?ArrResults是在嵌套的for循环中更新的,那么它为什么不像这样显示在最后一个返回语句之后呢?
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (i = 0; i < ints.length; i++) {
for (j = 0; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
arrResults.push(ints[i]);
arrResults.push(ints[j]);
break;
}
}
if (arrResults !== []) {
break;
}
}
return arrResults;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
解决方案
一个数组与另一个数组的比较错误(没有相同的对象引用)
a = []
b = []
a === b // false
// other example
a = []
b = a
a === b // true
用于检查长度,
a = []
a.length // 0
即使在使用循环的情况下,也可以使用几乎是二次的n?时间复杂度
i = 0; i < array.length - 1
j = i + 1; j < array.length
哪个大于n的一半,但为二次
您可以对已看到值的对象进行单循环。
此方法查找特定和的数组的第一对。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">function sumPairs(ints, s) {
const needed = {};
for (const value of ints) {
if (needed[value]) return [s - value, value];
needed[s - value] = true;
}
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
相关文章