-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathHeaps:FindtheRunningMedian.java
42 lines (32 loc) · 1.3 KB
/
Heaps:FindtheRunningMedian.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
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class FindTheRunningMedian {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
PriorityQueue<Double> small = new PriorityQueue<>(1, Collections.reverseOrder());
PriorityQueue<Double> large = new PriorityQueue<>(1);
StringBuilder sb = new StringBuilder();
double num, ans;
DecimalFormat df = new DecimalFormat("#.0");
for (int i = 0; i < n; i++) {
num = Integer.parseInt(sc.nextLine());
if(small.isEmpty() || (num < small.peek())) small.add(num);
else if(large.isEmpty() || (num > large.peek())) large.add(num);
else small.add(num);
while(small.size() > large.size()+1) {
large.add(small.poll());
}
while(large.size() > small.size()) {
small.add(large.poll());
}
if(small.size() == large.size()) ans = (small.peek() + large.peek())/2;
else if(small.size() < large.size()) ans = large.peek();
else ans = small.peek();
sb.append(df.format(ans)+"\n");
}
System.out.println(sb.toString());
sc.close();
}
}