【问题标题】:My nested for loop times out when searching for 2 numbers in an array that add up to a sum value在数组中搜索两个加起来为总和值的数字时,我的嵌套 for 循环超时
【发布时间】:2021-01-28 08:26:23
【问题描述】:

我试图找到一种更好/更快的算法,当我尝试在一个数字数组中找到任何两个数字时,该算法的总和为一个总和(例如 s)。我需要返回加起来为 sum(s) 的一对数字,其中也有出现最早的索引(可能还有许多其他对)。这是我的嵌套 for 循环方法。

function sum(ints, s){
  let pusher = [];
  let count = 1000;
  for(let i = 0; i < ints.length; i++){
      for(let j = i+1; j < ints.length; j++){
        if(ints[i] + ints[j] === s){
          if(j < count){
            pusher = [ints[i],ints[j]];
            count = j;  
          }
        } 
    }
  }
  return pusher.length > 0 ? pusher : undefined ;
}

【问题讨论】:

  • 超时?您能否展示一个“超时”的函数的参数示例 - 如果这会导致浏览器停止代码,您必须将一个巨大的数组作为 ints 传递
  • 这适用于简单的较小数组,例如 let array = [1, 9, 15, 2, 4, 7, 5] let s = 6;应该返回 [2,4] 而不是 [1,5]。
  • 所以,算法是错误的,但你的问题是关于“超时”而不是准确性 - 无论如何...... 1 + 5 = 6......这将是找到的第一个结果
  • 不是真的,只是超长数组。我认为时间限制在 12 秒以下。我想我正在看看是否有人可以帮助我制定更快的算法。否,因为 j 的索引为 6,而对于 2 和 4,j 的索引为 4。
  • 它实际上确实为您的示例返回 [2,4] - 仍然与您的问题无关

标签: javascript algorithm function for-loop nested-loops


【解决方案1】:

为了将计算复杂度从 O(n ^ 2) 降低到 O(n),请创建一个 Set 而不是。迭代一个数字时,检查该集合是否具有值 sum - num - 如果是,则返回该对作为结果。否则,将数字放入 Set 中:

或者你可以使用一个集合

function sum(ints, sum) {
  const set = new Set();
  for (const num of ints) {
    const otherNum = sum - num;
    if (set.has(otherNum)) {
      return [num, otherNum];
    } else {
      set.add(num);
    }
  }
}
console.log(sum([3, 4, 99, -2, 55, 66, -3], 1));
console.log(sum([1, 9, 15, 2, 4, 7, 5], 6));

【讨论】:

  • 谢谢,我需要了解更多关于集合的信息,但这似乎解决了超时问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2021-09-15
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 2019-11-12
相关资源
最近更新 更多