Design a data structure that receives a stream of integers via addNum and returns the median of everything so far via findMedian. Input is a LeetCode-style list of operations.
A max-heap holds the smaller half and a min-heap the larger half, with the max-heap allowed one extra. The median is the max-heap's top, or the average of both tops.
1class MedianFinder {2low = new MaxPriorityQueue<number>(); // smaller half3high = new MinPriorityQueue<number>(); // larger half4addNum(num: number): void {5this.low.enqueue(num);6this.high.enqueue(this.low.dequeue());7if (this.high.size() > this.low.size()) this.low.enqueue(this.high.dequeue());8}9findMedian(): number {10return this.low.size() > this.high.size() ? this.low.front() : (this.low.front() + this.high.front()) / 2;11}12}
Two empty heaps.
Space: play/pause · ←/→: step