【问题标题】:How can I reduce big O (n ^ 2) complexity of two for loops如何降低两个 for 循环的大 O (n ^ 2) 复杂度
【发布时间】:2021-11-26 01:48:49
【问题描述】:

我有 2 个数组(txs 和间隔),我希望间隔包括日期介于 from 和 to(包括)之间的 txs。

const txs = [
   { price: 1, date: 1 },
   { price: 3, date: 2 },
   { price: 1.7, date: 4 }
];
const interval = [
   { from: 1, to: 2, txs: [] },
   { from: 2, to: 3, txs: [] },
   { from: 3, to: 4, txs: [] }
];

预期结果

[
   { from: 1, to: 2, txs: [{ price: 1 }, { price: 3 }] },
   { from: 2, to: 3, txs: [{ price: 3 }] },
   { from: 3, to: 4, txs: [{ price: 1.7 }] }
]

这是我在 O(n^2) 中的解决方案

for (let i of interval) {
  for (let j of txs) {
     if (j.date >= i.from && j.date <= i.to) {
        i.txs.push({ price: j.price });
     }
  }
}

这只是一个例子。真正的一个 txs 和间隔可能有超过 10,000 个元素。 有没有可以在 O(n) 或 O(n log n) 中完成的解决方案?

【问题讨论】:

  • interval的元素数量和txs的元素数量上这不是O(n)吗?
  • @Frederik 这只是一个例子。真正的一个 txs 和间隔可能有超过 10,000 个元素。
  • 您可以通过对txs 数组进行排序进行优化,并在嵌套循环中进行二进制搜索而不是迭代。然后你得到n + log(n),它比n^2略好。
  • 如果区间数组有不同的区间值,可以删除所有推送的txs数组元素。因此,“for (let j of txs)”的迭代次数低于 start

标签: javascript algorithm big-o


【解决方案1】:

让我称txs nintervals m 的长度。在cucaracho's hint 之后,您有一个 O(nlog(n)) 预计算。查找要包含的 first“txs”(如果有)需要 O(logn) 每个间隔。添加一个 tx 需要 O(1) 总共 O(nlog(n) + mlog(n) +mn) = O((n+m)log(n) +mn)。
要从图片中删除那个烦人的术语 mn(“输出大小”),请找到要包含的第一个 txs not,并且对于每个间隔,通过指定来表示要包含的 txss这是第一个之外的一个。

对于非重叠间隔,仅对两个数组排序并同时遍历两者可能会更快,其中一个影响是相对数组大小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-08
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多