-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMedianOfAges.java
49 lines (43 loc) · 1.67 KB
/
MedianOfAges.java
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
42
43
44
45
46
47
48
49
import java.util.Collections;
import java.util.PriorityQueue;
public class MedianOfAges {
// 2 priority queues to store the lower half and the upper half
private PriorityQueue<Integer> maxHeap;
private PriorityQueue<Integer> minHeap;
public MedianOfAges() {
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
minHeap = new PriorityQueue<>();
}
// Inserting the number to the correct heap
public void insertNum(int num) {
if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
maxHeap.add(num);
} else {
minHeap.add(num);
}
// Balancing the heaps according to their sizes to keep the median
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.add(maxHeap.poll());
} else if (minHeap.size() > maxHeap.size()) {
maxHeap.add(minHeap.poll());
}
}
// Finding the median
public double findMedian() {
if (maxHeap.size() == minHeap.size()) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
} else {
return maxHeap.peek();
}
}
public static void main(String[] args) {
MedianOfAges medianOfAges = new MedianOfAges();
medianOfAges.insertNum(22);
medianOfAges.insertNum(35);
System.out.println("The recommended content will be for ages under: " + medianOfAges.findMedian());
medianOfAges.insertNum(30);
System.out.println("The recommended content will be for ages under: " + medianOfAges.findMedian());
medianOfAges.insertNum(25);
System.out.println("The recommended content will be for ages under: " + medianOfAges.findMedian());
}
}