





















By Long Luo
This article is the solution Two Heaps with the Follow Up’s Solution of Problem 295. Find Median from Data Stream .
We can simply use a \(\texttt{ArrayList}\) to record the number and sort the list, then we can easily get the median element of the list. However, the Time Complexity will be \(O(n^2 \log n)\) and the Space Complexity is \(O(n)\) .
It surely will be TLE and we have to find a better solution.
We can use Two Priority Queues (Heaps) to maintain the data of the entire data stream.
The min Heap denoted as \(\textit{queueMin}\) is used to maintain the number \(\textit{num} \leq \textit{median}\). The max Heap denoted as \(\textit{queueMax}\) is used to maintain the number \(\textit{num} \gt \textit{median}\) .
When the total number of data stream elements is Even: \(\texttt{queueMax.size()} = \texttt{queueMin.size()}\) , the dynamic median is \(\dfrac {\texttt{queueMax.peek()} + \texttt{queueMin.peek()}}{2}\) ;
When the total number of data stream elements is Odd: \(\texttt{queueMin.size()} = \texttt{queueMin.size()} + 1\) , the dynamic median is \(\texttt{queueMin.peek()}\) .
When we try to add a new number \(\textit{num}\) to the Two Heaps, the cases can be as follows:
We need to add this number to \(\textit{queueMin}\). The new median will be less than or equal to the original median, so we may need to move the \(\texttt{queueMin.peek()}\) to \(\textit{queueMax}\) .
We need to add this number to \(\textit{queueMax}\). The new median will be greater than or equal to the original median, so we may need to move the \(\texttt{queueMax.peek()}\) to \(\textit{queueMin}\) .
1 | static class MedianFinder { |
All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)
Explore More Leetcode Solutions. 😉😃💗
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。