-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay45.java
More file actions
41 lines (34 loc) · 1.11 KB
/
Day45.java
File metadata and controls
41 lines (34 loc) · 1.11 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
39
40
41
import java.util.PriorityQueue;
class MedianFinder {
PriorityQueue<Integer> maxHeap;
PriorityQueue<Integer> minHeap;
public MedianFinder() {
maxHeap = new PriorityQueue<>((a, b) -> b - a);
minHeap = new PriorityQueue<>();
}
public void addNum(int num) {
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
if (maxHeap.size() < minHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
public double findMedian() {
if (maxHeap.size() == minHeap.size()) {
// If the size is even, return the average of the two middle elements
return (maxHeap.peek() + minHeap.peek()) / 2.0;
} else {
return maxHeap.peek();
}
}
}
public class Day45 {
public static void main(String[] args) {
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);
medianFinder.addNum(2);
System.out.println(medianFinder.findMedian()); // Output: 1.5
medianFinder.addNum(3);
System.out.println(medianFinder.findMedian()); // Output: 2.0
}
}