鑒于以下問題:“存儲數字流中最大的5000個數字”想到的解決方案是一個二叉搜索樹,該樹維護該樹中節點數的計數,并在計數達到5000時引用最小節點。當計數達到5000時,可以將要添加的每個新數字進行比較。樹上最小的項目。如果更大,則可以添加新的數字,然后刪除最小的數字,并計算出新的最小數字(這很簡單,因為已經具有先前的最小數字)。我對此解決方案的擔心是,二叉樹自然會偏斜(因為我只是在一側刪除)。有沒有一種方法可以解決這個問題,而又不會造成嚴重歪斜的樹?如果有人需要,到目前為止,我為我的解決方案提供了偽代碼:process(number){ if (count == 5000 && number > smallest.Value) { addNode( root, number) smallest = deleteNodeAndGetNewSmallest ( root, smallest) }}deleteNodeAndGetNewSmallest( lastSmallest){ if ( lastSmallest has parent) { if ( lastSmallest has right child) { smallest = getMin(lastSmallest.right) lastSmallest.parent.right = lastSmallest.right } else { smallest = lastSmallest.parent } } else { smallest = getMin(lastSmallest.right) root = lastSmallest.right } count-- return smallest}getMin( node){ if (node has left) return getMin(node.left) else return node}add(number){ //standard implementation of add for BST count++}
3 回答

慕容森
TA貢獻1853條經驗 獲得超18個贊
您可以使用選擇算法查找前k個元素,但通過存儲2k個元素的數組僅使用O(k)內存。每次填充數組時,請使用選擇算法刪除最低的k。不管k的值如何,這都會花費O(n)時間,因為您正在執行O(n / k)選擇算法,每個算法都花費時間O(k)。它還僅使用O(k)內存。
添加回答
舉報
0/150
提交
取消