Find Median from Data Stream
ID: 81; hard
Solution 1 (Java)
Notes
We used a
maxHeap
and aminHeap
to maintain the data stream. ThemaxHeap
stores numbers that are less than themedian
. TheminHeap
stores numbers that are larger than themedian
. Then, we update the median whenever the two heaps have sizes that differ by 2 (to be more precise, see the condition in code). By construction, the results by polling either theminHeap
or themaxHeap
will be the currentmedian
. Eventually, we just return the currentmedian
.The reason is that we need to find the median of
k
numbers, so it is natural to find thek/2
th largest number and thek/2
th smallest number (first number in each heap).
Last updated