[英]How can I reduce big O (n ^ 2) complexity of two for loops
我有 2 arrays(txs 和間隔),我希望間隔包括 txs,其日期介於 from 和 to(包括)之間。
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 和 interval 可能有超過 10,000 個元素。 有沒有可以在 O(n) 或 O(n log n) 中完成的解決方案?
讓我稱txs
的長度為n , intervals
的長度為m 。 按照cucaracho 的提示,您有一個 O( n log( n )) 預計算。 查找要包含的第一個“txs”(如果有的話)需要每個時間間隔 O(log n )。 添加一個 tx 應該花費 O(1),總共 O( n log( n ) + m log( n ) + mn ) = O(( n + m ) log( n ) + mn )。
要從圖片中去除煩人的術語mn (“輸出大小”),請找到第一個不包含的 txs,並且對於每個間隔,通過在第一個之外指定這個 txs 來表示要包含的 txss。
對於非重疊間隔,僅對 arrays 進行排序並同時步行可能會更快,其中一個影響因素是相對數組大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.