Skip to content

Commit 929e329

Browse files
authored
Efficient Median Finder Using Two Heaps in Java (#3564)
2 parents 3f85e52 + cbf17c9 commit 929e329

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)