【问题标题】:JS for loop in for loop, problem with scope I guessJS for循环在for循环中,我猜范围有问题
【发布时间】:2021-10-25 00:34:55
【问题描述】:

输入是一个数组 ints [11, 2, 7, 8, 4, 6] 和整数 s 10。功能是输出一个数组,其中包含一对来自 int 的两个数字,它们首先形成 10 的和. 所以这里的输出应该是[2, 8],因为2 + 8 = 10。为什么输出的是空数组呢? arrResults 是在嵌套的 for 循环中更新的,为什么在最后的 return 语句之后没有显示出来呢?

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));

【问题讨论】:

  • 在 for 循环中我认为你应该这样做 let i=0let j = 0
  • 我刚试过,但没有任何区别。
  • 你的第二个循环是错误的,你不应该从零开始。
  • 只要找到 sumoftwo === s 就可以返回 [ints[i],ints[j]] 而不是生成结果数组
  • arrResults !== [] 不是查看数组是否有元素的方式,因此您的问题

标签: javascript for-loop scope nested-loops


【解决方案1】:

除了一个数组与另一个数组的错误比较(没有相同的对象引用)

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² 的一半,但仍是二次方,

您可以使用已看到值的对象进行单循环

这种方法会找到数组的第一对和某个总和。

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));

【讨论】:

  • 非常聪明的答案.. 在 O(n) 中。不错。
  • Nina Scholz 感谢您提供这个惊人的解决方案,我花了一段时间才掌握它,现在我明白了它是如何工作的,我很惊讶它是如此简单:-) 神奇!
【解决方案2】:

您的代码失败,因为您正在检查数组是否为空。问题是 check 永远不会是假的,所以它在第一次迭代时就退出了。

console.log([]===[]);
console.log([]!==[]);

所以代码要进行更改以提高性能并退出

function sumPairs(ints, s) {
  let arrResults = [];
  let sumOfTwo;
  for (let i = 0; i < ints.length; i++) {
    for (let j = i + 1; j < ints.length; j++) {
      sumOfTwo = ints[i] + ints[j];
      if (sumOfTwo === s) {
        arrResults.push(ints[i]);
        arrResults.push(ints[j]);
        break;
      }
    }
    if (arrResults.length) {
      break;
    }
  }
  return arrResults;
}

console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));

不需要两次突围,返回数组即可

function sumPairs(ints, s) {
  let arrResults = [];
  let sumOfTwo;
  for (let i = 0; i < ints.length; i++) {
    for (let j = i + 1; j < ints.length; j++) {
      sumOfTwo = ints[i] + ints[j];
      if (sumOfTwo === s) {
        return [ints[i], ints[j]];
      }
    }
  }
  return null;
}

console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2020-09-26
    相关资源
    最近更新 更多