-
Notifications
You must be signed in to change notification settings - Fork 0
/
RunningMedian.java
46 lines (36 loc) · 1.07 KB
/
RunningMedian.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
import java.util.*;
public class RunningMedian {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
PriorityQueue<Integer> minQ = new PriorityQueue<Integer>(n);
minQ.add(Integer.MAX_VALUE);
PriorityQueue<Integer> maxQ = new PriorityQueue<Integer>(n, Collections.reverseOrder());
maxQ.add(Integer.MIN_VALUE);
int a;
float median = 0;
for (int i = 0; i<n;i++) {
a = in.nextInt();
// adding the number to proper heap
if (a >= minQ.peek())
minQ.add(a);
else
maxQ.add(a);
// balancing the heaps
if (minQ.size() - maxQ.size() == 2)
maxQ.add(minQ.poll());
else if (maxQ.size() - minQ.size() == 2)
minQ.add(maxQ.poll());
// returning the median
if (minQ.size() == maxQ.size())
median = ((float)minQ.peek() + (float)maxQ.peek()) / 2;
else if (minQ.size() > maxQ.size())
median = minQ.peek();
else
median = maxQ.peek();
System.out.println(median);
}
in.close();
}
}