File tree 2 files changed +95
-0
lines changed
main/java/com/leetcode/twoheaps
test/java/com/leetcode/twoheaps
2 files changed +95
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .leetcode .twoheaps ;
2
+
3
+ import java .util .Comparator ;
4
+ import java .util .PriorityQueue ;
5
+
6
+ public final class MedianFinder {
7
+
8
+
9
+ private static final int TWO = 2 ;
10
+ private final PriorityQueue <Integer > maxHeap ;
11
+ private final PriorityQueue <Integer > minHeap ;
12
+ private Double median ;
13
+
14
+ public MedianFinder () {
15
+ this .maxHeap = new PriorityQueue <>(Comparator .reverseOrder ());
16
+ this .minHeap = new PriorityQueue <>();
17
+ }
18
+
19
+ public void addNum (int num ) {
20
+ if (maxHeap .isEmpty ()) {
21
+ maxHeap .add (num );
22
+ } else {
23
+ final int size = size ();
24
+ if (size % TWO == 0 ) {
25
+ if (num < minHeap .peek ()) {
26
+ maxHeap .add (num );
27
+ } else {
28
+ maxHeap .add (minHeap .remove ());
29
+ minHeap .add (num );
30
+ }
31
+ } else {
32
+ if (num < maxHeap .peek ()) {
33
+ minHeap .add (maxHeap .remove ());
34
+ maxHeap .add (num );
35
+ } else {
36
+ minHeap .add (num );
37
+ }
38
+ }
39
+ }
40
+ median = null ;
41
+ }
42
+
43
+ public double findMedian () {
44
+ if (median == null ) {
45
+ median = calcMedian ();
46
+ }
47
+ return median ;
48
+ }
49
+
50
+ private double calcMedian () {
51
+ int size = size ();
52
+ if (size % TWO == 0 ) {
53
+ if (minHeap .isEmpty () || maxHeap .isEmpty ()) {
54
+ throw new IllegalStateException ();
55
+ }
56
+ return (minHeap .peek ().doubleValue () + maxHeap .peek ()) / TWO ;
57
+ } else {
58
+ if (maxHeap .isEmpty ()) {
59
+ throw new IllegalStateException ();
60
+ }
61
+ return maxHeap .peek ().doubleValue ();
62
+ }
63
+ }
64
+
65
+ private int size () {
66
+ return minHeap .size () + maxHeap .size ();
67
+ }
68
+ }
Original file line number Diff line number Diff line change
1
+ package com .leetcode .twoheaps ;
2
+
3
+ import org .junit .jupiter .api .DisplayName ;
4
+ import org .junit .jupiter .api .Test ;
5
+
6
+ import static org .junit .jupiter .api .Assertions .assertEquals ;
7
+
8
+ class MedianFinderTest {
9
+
10
+ public static final double EPS = 10e-6 ;
11
+
12
+ @ Test
13
+ @ DisplayName ("Testing MedianFinder API" )
14
+ void test () {
15
+ final MedianFinder finder = new MedianFinder ();
16
+ finder .addNum (1 );
17
+ assertEquals (1 , finder .findMedian (), EPS );
18
+ finder .addNum (2 );
19
+ assertEquals (1.5 , finder .findMedian (), EPS );
20
+ finder .addNum (3 );
21
+ assertEquals (2 , finder .findMedian (), EPS );
22
+ finder .addNum (-1 );
23
+ assertEquals (1.5 , finder .findMedian (), EPS );
24
+ finder .addNum (-3 );
25
+ assertEquals (1 , finder .findMedian (), EPS );
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments