Skip to content

Commit cbf17c9

Browse files
Efficient Median Finder Using Two Heaps in Java
This implementation provides an optimized solution for finding the median of a dynamically updating data stream. It uses two priority queues (heaps) to maintain balance between the lower and upper halves of the dataset. The max heap stores the smaller half of the elements, while the min heap stores the larger half.
1 parent 3f85e52 commit cbf17c9

File tree

1 file changed

+33
-19
lines changed

1 file changed

+33
-19
lines changed
Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,37 @@
1+
import java.util.Collections;
2+
import java.util.PriorityQueue;
3+
import java.util.Queue;
4+
15
class MedianFinder {
2-
public void addNum(int num) {
3-
if (maxHeap.isEmpty() || num <= maxHeap.peek())
4-
maxHeap.offer(num);
5-
else
6-
minHeap.offer(num);
76

8-
9-
if (maxHeap.size() < minHeap.size())
10-
maxHeap.offer(minHeap.poll());
11-
else if (maxHeap.size() - minHeap.size() > 1)
12-
minHeap.offer(maxHeap.poll());
13-
}
7+
private Queue<Integer> maxHeap;
8+
private Queue<Integer> minHeap;
9+
10+
public MedianFinder() {
11+
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
12+
minHeap = new PriorityQueue<>();
13+
}
14+
15+
public void addNum(int num) {
16+
17+
if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
18+
maxHeap.offer(num);
19+
} else {
20+
minHeap.offer(num);
21+
}
1422

15-
public double findMedian() {
16-
if (maxHeap.size() == minHeap.size())
17-
return (double) (maxHeap.peek() + minHeap.peek()) / 2.0;
18-
return (double) maxHeap.peek();
19-
}
23+
24+
if (maxHeap.size() < minHeap.size()) {
25+
maxHeap.offer(minHeap.poll());
26+
} else if (maxHeap.size() - minHeap.size() > 1) {
27+
minHeap.offer(maxHeap.poll());
28+
}
29+
}
2030

21-
private Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
22-
private Queue<Integer> minHeap = new PriorityQueue<>();
23-
}
31+
public double findMedian() {
32+
if (maxHeap.size() == minHeap.size()) {
33+
return (maxHeap.peek() + minHeap.peek()) / 2.0;
34+
}
35+
return maxHeap.peek();
36+
}
37+
}

0 commit comments

Comments
 (0)