File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ package Heap ;
2
+
3
+ // Problem Statement: Find the Median of a Number Stream (medium)
4
+ // LeetCode Question: 295. Find Median from Data Stream
5
+
6
+ import java .util .PriorityQueue ;
7
+
8
+ public class Problem_1_Median_Of_A_Number_Stream {
9
+
10
+ PriorityQueue <Integer > maxHeap ;
11
+ PriorityQueue <Integer > minHeap ;
12
+
13
+ public Problem_1_Median_Of_A_Number_Stream () {
14
+ maxHeap = new PriorityQueue <>((a , b ) -> b - a );
15
+ minHeap = new PriorityQueue <>((a , b ) -> a - b );
16
+ }
17
+
18
+ public void insertNum (int num ){
19
+ if (maxHeap .isEmpty () || maxHeap .peek () >= num ) {
20
+ maxHeap .add (num );
21
+ } else {
22
+ minHeap .add (num );
23
+ }
24
+ if (maxHeap .size () > minHeap .size () + 1 ) {
25
+ minHeap .add (maxHeap .poll ());
26
+ } else if (maxHeap .size () < minHeap .size ()) {
27
+ maxHeap .add (minHeap .poll ());
28
+ }
29
+ }
30
+
31
+ public double findMedian (){
32
+ if (maxHeap .size () == minHeap .size ()) {
33
+ return maxHeap .peek () / 2.0 + minHeap .peek () / 2.0 ;
34
+ }
35
+ return maxHeap .peek ();
36
+ }
37
+
38
+ }
You can’t perform that action at this time.
0 commit comments