Skip to content

Commit a9289c9

Browse files
committed
solve find median from data stream
1 parent 1426c17 commit a9289c9

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public class MedianFinder {
2+
private PriorityQueue<Integer> maxHeap;
3+
private PriorityQueue<Integer> minHeap;
4+
5+
public MedianFinder() {
6+
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
7+
minHeap = new PriorityQueue<>();
8+
}
9+
10+
public void addNum(int num) {
11+
maxHeap.offer(num);
12+
minHeap.offer(maxHeap.poll());
13+
14+
if (minHeap.size() > maxHeap.size()) {
15+
maxHeap.offer(minHeap.poll());
16+
}
17+
}
18+
19+
public double findMedian() {
20+
if (maxHeap.size() > minHeap.size()) {
21+
return maxHeap.peek();
22+
} else {
23+
return (maxHeap.peek() + minHeap.peek()) / 2.0;
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)