150強訪談

從資料流中尋找中值

「從資料流中尋找中位數」問題的詳細指南和 Python 實作。

問題陳述

中位數是有序整數列表中的中間值。如果清單的大小是偶數,則沒有中間值,中位數是中間兩個值的平均值。

實作 MedianFinder 類別:

- MedianFinder() 初始化 MedianFinder 物件。

- addNum(num: int) 將資料流中的整數 num 加入資料結構。

- findMedian() -> float 傳回到目前為止所有元素的中位數。

輸入是操作和參數的清單。實作一個傳回結果清單的函數 medianFinder(operations: list, arguments: list) -> list (建構子/addNum 為 None,findMedian 為 float)。

約束條件
  • -10^5 <= num <= 10^5
  • There will be at least one element in the data structure before calling findMedian
  • At most 5 * 10^4 calls will be made to addNum and findMedian

範例

Example 1
Input
operations = ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"], arguments = [[], [1], [2], [], [3], []]
Output
[None, None, None, 1.5, None, 2.0]
Explanation

Initialize. Add 1, 2. Median is 1.5. Add 3. Median is 2.0.

Need a Hint?
考慮使用堆/優先權佇列特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。