-
Notifications
You must be signed in to change notification settings - Fork 11
/
FindTheRunningMedian.java
60 lines (51 loc) Β· 2.05 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package heap;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class FindTheRunningMedian {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int length = scanner.nextInt();
int[] array = getArray(length);
printMedians(array);
}
private static int[] getArray(int length) {
int[] array = new int[length];
for (int index = 0 ; index < array.length ; index++) {
array[index] = scanner.nextInt();
}
return array;
}
private static void printMedians(int[] array) {
Queue<Integer> lowerHalf = new PriorityQueue<>(Comparator.reverseOrder());
Queue<Integer> upperHalf = new PriorityQueue<>();
for (int number : array) {
addToHeap(lowerHalf, upperHalf, number);
redolenceHeaps(lowerHalf, upperHalf);
double median = getMedian(lowerHalf, upperHalf);
System.out.println(String.format("%.1f", median));
}
}
private static void addToHeap(Queue<Integer> lowerHalf, Queue<Integer> upperHalf, int number) {
if (lowerHalf.isEmpty() || number < lowerHalf.peek()) {
lowerHalf.add(number);
} else {
upperHalf.add(number);
}
}
private static void redolenceHeaps(Queue<Integer> lowerHalf, Queue<Integer> upperHalf) {
Queue<Integer> larger = lowerHalf.size() < upperHalf.size() ? upperHalf : lowerHalf ;
Queue<Integer> smaller = lowerHalf.size() < upperHalf.size() ? lowerHalf : upperHalf ;
while (larger.size() - smaller.size() >= 2) {
smaller.add(larger.poll());
}
}
private static double getMedian(Queue<Integer> lowerHalf, Queue<Integer> upperHalf) {
if (lowerHalf.size() == upperHalf.size()) {
return ((double) lowerHalf.peek() + upperHalf.peek()) / 2;
} else {
return lowerHalf.size() > upperHalf.size() ? lowerHalf.peek() : upperHalf.peek();
}
}
}