LeetCode 295: Find Median from Data Stream
Problem Description
Explanation:
To find the median from a data stream efficiently, we can use two priority queues - one max heap to store the lower half of the elements and one min heap to store the higher half of the elements. By maintaining these two heaps, we can obtain the median in constant time.
Here's how the algorithm works:
- Initialize two priority queues:
maxHeap
to store the smaller half of elements andminHeap
to store the larger half of elements. - When adding a new number:
- Add the number to
maxHeap
. - If the size of
maxHeap
is greater than the size ofminHeap
or the top element ofmaxHeap
is greater than the new number, pop the top element frommaxHeap
and push it tominHeap
. - If the size of
minHeap
is greater than the size ofmaxHeap
, pop the top element fromminHeap
and push it tomaxHeap
.
- Add the number to
- To find the median:
- If the size of
maxHeap
andminHeap
is the same, return the average of their top elements. - Otherwise, return the top element of the heap with more elements.
- If the size of
Solutions
import java.util.PriorityQueue;
class MedianFinder {
PriorityQueue<Integer> maxHeap;
PriorityQueue<Integer> minHeap;
public MedianFinder() {
maxHeap = new PriorityQueue<>((a, b) -> b - a);
minHeap = new PriorityQueue<>();
}
public void addNum(int num) {
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
if (maxHeap.size() < minHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
public double findMedian() {
if (maxHeap.size() == minHeap.size()) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
} else {
return maxHeap.peek();
}
}
}
Related LeetCode Problems
Loading editor...