File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ //295. Find Median from Data Stream
2
+ class MedianFinder {
3
+ public void addNum (int num ) {
4
+ if (maxHeap .isEmpty () || num <= maxHeap .peek ())
5
+ maxHeap .offer (num );
6
+ else
7
+ minHeap .offer (num );
8
+
9
+ // Balance two heaps s.t.
10
+ // |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1
11
+ if (maxHeap .size () < minHeap .size ())
12
+ maxHeap .offer (minHeap .poll ());
13
+ else if (maxHeap .size () - minHeap .size () > 1 )
14
+ minHeap .offer (maxHeap .poll ());
15
+ }
16
+
17
+ public double findMedian () {
18
+ if (maxHeap .size () == minHeap .size ())
19
+ return (double ) (maxHeap .peek () + minHeap .peek ()) / 2.0 ;
20
+ return (double ) maxHeap .peek ();
21
+ }
22
+
23
+ private Queue <Integer > maxHeap = new PriorityQueue <>(Collections .reverseOrder ());
24
+ private Queue <Integer > minHeap = new PriorityQueue <>();
25
+ }
You can’t perform that action at this time.
0 commit comments