Find Median From Data Stream
Detailed guide and Python implementation for the 'Find Median From Data Stream' problem.
1. 学ぶ
The 'Find Median From Data Stream' problem is a key challenge in the Heap / Priority Queue section.
This implementation focuses on hard-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Find Median From Data Stream.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Find Median From Data Stream carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
問題提起
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
Implement the MedianFinder class:
- MedianFinder() Initializes the MedianFinder object.
- addNum(num: int) Adds the integer num from the data stream to the data structure.
- findMedian() -> float Returns the median of all elements so far.
Input is a list of operations and arguments. Implement a function medianFinder(operations: list, arguments: list) -> list that returns a list of results (None for constructor/addNum, float for findMedian).
- •-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
例
operations = ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"], arguments = [[], [1], [2], [], [3], []]
[None, None, None, 1.5, None, 2.0]
Initialize. Add 1, 2. Median is 1.5. Add 3. Median is 2.0.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
解決する準備はできましたか?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
インタビューの洞察とバリエーション
複雑さの分析の内訳
なぜ時間がかかるのか: Directly evaluates all possibilities.
なぜ宇宙なのか: Uses standard local memory.
なぜ時間がかかるのか: Optimized paths reduce total operations.
なぜ宇宙なのか: May trade memory for speed.
最適化されたソリューションの Python コード
最適化されたソリューションの Python コード
import heapq
class MedianFinderOpt:
def __init__(self):
self.small, self.large = [], []
def addNum(self, num):
heapq.heappush(self.small, -1 * num)
if self.small and self.large and (-1 * self.small[0]) > self.large[0]:
val = -1 * heapq.heappop(self.small)
heapq.heappush(self.large, val)
if len(self.small) > len(self.large) + 1:
val = -1 * heapq.heappop(self.small)
heapq.heappush(self.large, val)
if len(self.large) > len(self.small) + 1:
val = heapq.heappop(self.large)
heapq.heappush(self.small, -1 * val)
def findMedian(self):
if len(self.small) > len(self.large): return -1 * self.small[0]
if len(self.large) > len(self.small): return self.large[0]
return (-1 * self.small[0] + self.large[0]) / 2ブルート フォース コード (スポイラーガード付き)
ブルート フォース コード (スポイラーガード付き)
class MedianFinderBrute:
def __init__(self):
self.nums = []
def addNum(self, num):
self.nums.append(num)
def findMedian(self):
self.nums.sort()
n = len(self.nums)
if n % 2: return self.nums[n//2]
return (self.nums[n//2-1] + self.nums[n//2]) / 2Algorithm Pattern Checklist
When dealing with Heap / Priority Queue data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
Standard Heap / Priority Queue problem properties apply.
関連する質問
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
推奨される Python リソース
関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。
Python ループ
Python ループを使用してデータを反復処理する方法を学びます。インタラクティブな例を使用して、for ループ、while ループ、ブレーク、継続、ループのベスト プラクティスをマスターします。
Python でリストから重複を削除する方法
順序を維持または無視しながら、Python でリストから重複を削除する方法を学びます。セット変換、辞書キー、ループ メソッドを比較します。
Python のコレクションとデータ構造のチートシート
Python コレクション モジュールとネイティブ データ構造の完全なガイド。リスト、辞書、セット、タプル、デク、名前付きタプルについて学びます。
Python と JavaScript: どちらのプログラミング言語が最適ですか?
Python と JavaScript の包括的な比較。構文の違い、パフォーマンス、使用例 (バックエンドとフロントエンド)、およびコーディング例を調べます。