|
1 | 1 | class MedianFinder {
|
2 |
| - |
3 |
| - private PriorityQueue<Integer> small; |
4 |
| - private PriorityQueue<Integer> large; |
5 |
| - |
6 |
| - public MedianFinder() { |
7 |
| - this.small = new PriorityQueue<>((a, b) -> b - a); |
8 |
| - this.large = new PriorityQueue<>(); |
9 |
| - } |
10 |
| - |
11 |
| - public void addNum(int num) { |
12 |
| - small.add(num); |
13 |
| - large.add(small.remove()); |
14 |
| - if (large.size() > small.size()) { |
15 |
| - small.add(large.remove()); |
| 2 | + |
| 3 | + private final PriorityQueue<Integer> minQueue; |
| 4 | + private final PriorityQueue<Integer> maxQueue; |
| 5 | + |
| 6 | + public MedianFinder() { |
| 7 | + this.minQueue = new PriorityQueue<>(); |
| 8 | + this.maxQueue = new PriorityQueue<>((a, b) -> b - a); |
16 | 9 | }
|
17 |
| - } |
18 |
| - |
19 |
| - public double findMedian() { |
20 |
| - if (small.size() > large.size()) { |
21 |
| - return small.peek(); |
| 10 | + |
| 11 | + public void addNum(int num) { |
| 12 | + maxQueue.add(num); |
| 13 | + minQueue.add(maxQueue.poll()); |
| 14 | + if (maxQueue.size() < minQueue.size()) { |
| 15 | + maxQueue.add(minQueue.poll()); |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + public double findMedian() { |
| 20 | + return maxQueue.size() > minQueue.size() ? |
| 21 | + ((double) maxQueue.peek()) : |
| 22 | + ((maxQueue.peek() + minQueue.peek()) / (2.0)); |
22 | 23 | }
|
23 |
| - return (small.peek() + large.peek()) / 2.0; |
24 |
| - } |
25 | 24 | }
|
26 | 25 |
|
27 | 26 | /**
|
|
0 commit comments