-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_1_Median_Of_A_Number_Stream.java
More file actions
38 lines (30 loc) · 1.02 KB
/
Problem_1_Median_Of_A_Number_Stream.java
File metadata and controls
38 lines (30 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package Heap;
// Problem Statement: Find the Median of a Number Stream (medium)
// LeetCode Question: 295. Find Median from Data Stream
import java.util.PriorityQueue;
public class Problem_1_Median_Of_A_Number_Stream {
PriorityQueue<Integer> maxHeap;
PriorityQueue<Integer> minHeap;
public Problem_1_Median_Of_A_Number_Stream() {
maxHeap = new PriorityQueue<>((a, b) -> b - a);
minHeap = new PriorityQueue<>((a, b) -> a - b);
}
public void insertNum(int num){
if (maxHeap.isEmpty() || maxHeap.peek() >= num) {
maxHeap.add(num);
} else {
minHeap.add(num);
}
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.add(maxHeap.poll());
} else if (maxHeap.size() < minHeap.size()) {
maxHeap.add(minHeap.poll());
}
}
public double findMedian(){
if (maxHeap.size() == minHeap.size()) {
return maxHeap.peek() / 2.0 + minHeap.peek() / 2.0;
}
return maxHeap.peek();
}
}