-
Notifications
You must be signed in to change notification settings - Fork 1
/
runningMedian.js
47 lines (41 loc) · 1.06 KB
/
runningMedian.js
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
const heap = require('./heap');
const runningMedian = _ => {
const minHeap = heap((a, b) => a - b);
const maxHeap = heap((a, b) => b - a);
const getMedian = _ => {
if (minHeap.length() === maxHeap.length()) {
return (minHeap.root() + maxHeap.root()) / 2;
}
return minHeap.length() > maxHeap.length()
? minHeap.root()
: maxHeap.root();
};
const hasToAddToMaxHeap = val => val < maxHeap.root();
const hasToAddToMinHeap = val => val > minHeap.root();
const addValue = val => {
if (hasToAddToMinHeap(val)) {
if (minHeap.length() > maxHeap.length()) {
const oldRoot = minHeap.remove();
maxHeap.insert(oldRoot);
}
minHeap.insert(val);
} else if (hasToAddToMaxHeap(val)) {
if (maxHeap.length() > minHeap.length()) {
const oldRoot = maxHeap.remove();
minHeap.insert(oldRoot);
}
maxHeap.insert(val);
} else { // can add to either
if (minHeap.length() <= maxHeap.length()) {
minHeap.insert(val);
} else {
maxHeap.insert(val);
}
}
};
return {
addValue,
getMedian
};
};
module.exports = runningMedian;