File tree 1 file changed +12
-15
lines changed 1 file changed +12
-15
lines changed Original file line number Diff line number Diff line change 1
1
class MedianFinder {
2
2
3
- /** initialize your data structure here. */
4
- PriorityQueue <Integer > smaller ;
5
- PriorityQueue < Integer > bigger ;
3
+ private PriorityQueue < Integer > small ;
4
+ private PriorityQueue <Integer > large ;
5
+
6
6
public MedianFinder () {
7
- smaller = new PriorityQueue <>((a , b ) -> b - a );
8
- bigger = new PriorityQueue <>();
7
+ this . small = new PriorityQueue <>((a , b ) -> b - a );
8
+ this . large = new PriorityQueue <>();
9
9
}
10
10
11
11
public void addNum (int num ) {
12
- smaller .add (num );
13
- bigger .add (smaller . poll ());
14
- if (smaller .size () < bigger .size ()) {
15
- smaller .add (bigger . poll ());
12
+ small .add (num );
13
+ large .add (small . remove ());
14
+ if (large .size () > small .size ()) {
15
+ small .add (large . remove ());
16
16
}
17
17
}
18
18
19
19
public double findMedian () {
20
- if (smaller .size () == 0 && bigger .size () == 0 ) {
21
- return 0.0 ;
20
+ if (small .size () > large .size ()) {
21
+ return small . peek () ;
22
22
}
23
- if (smaller .size () > bigger .size ()) {
24
- return (double ) smaller .peek ();
25
- }
26
- return ((double ) smaller .peek () + bigger .peek ()) / 2 ;
23
+ return (small .peek () + large .peek ()) / 2.0 ;
27
24
}
28
25
}
29
26
You can’t perform that action at this time.
0 commit comments