295. Find Median from Data Stream#
1class MedianFinder {
2 PriorityQueue<Integer> lowers;
3 PriorityQueue<Integer> highers;
4
5 public MedianFinder() {
6 lowers = new PriorityQueue<>(Collections.reverseOrder());
7 highers = new PriorityQueue<>();
8 }
9
10 public void addNum(int num) {
11 if (lowers.isEmpty() || num < lowers.peek()) {
12 lowers.add(num);
13 } else {
14 highers.add(num);
15 }
16
17 // re-balance
18 if (lowers.size() - highers.size() > 1) {
19 highers.add(lowers.remove());
20 }
21
22 if (highers.size() - lowers.size() > 1) {
23 lowers.add(highers.remove());
24 }
25 }
26
27 public double findMedian() {
28 if (lowers.size() > highers.size()) {
29 return lowers.peek();
30 } else if (highers.size() > lowers.size()) {
31 return highers.peek();
32 } else {
33 return ((double) highers.peek() + lowers.peek()) / 2;
34 }
35 }
36}