-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11279.js
96 lines (77 loc) · 2.23 KB
/
11279.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var readline = require("readline");
var r = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
r.on("line", function (line) {
input.push(line);
}).on("close", function () {
main(input);
process.exit();
});
class MaxHeap {
constructor() {
this.heap = [null]
}
insert(data) {
this.heap.push(data);
let curIdx = this.heap.length - 1;
let parentIdx = (curIdx / 2) >> 0;
while (curIdx > 1 && this.heap[parentIdx] < this.heap[curIdx]) {
[this.heap[parentIdx], this.heap[curIdx]] = [this.heap[curIdx], this.heap[parentIdx]]
curIdx = parentIdx;
parentIdx = (curIdx / 2) >> 0;
}
}
delete() {
if (this.heap.length === 1) {
return 0;
}
const max = this.heap[1];
if (this.heap.length <= 2) this.heap = [null];
else this.heap[1] = this.heap.pop();
let curIdx = 1;
let leftIdx = curIdx * 2;
let rightIdx = curIdx * 2 + 1;
if (!this.heap[rightIdx]) {
if (this.heap[leftIdx] > this.heap[curIdx]) {
[this.heap[leftIdx], this.heap[curIdx]] = [this.heap[curIdx], this.heap[leftIdx]];
}
return max;
}
while (this.heap[leftIdx] > this.heap[curIdx] || this.heap[rightIdx] > this.heap[curIdx]) {
const maxIdx = this.heap[leftIdx] < this.heap[rightIdx] ? rightIdx : leftIdx;
[this.heap[maxIdx], this.heap[curIdx]] = [this.heap[curIdx], this.heap[maxIdx]];
curIdx = maxIdx;
leftIdx = curIdx * 2;
rightIdx = curIdx * 2 + 1;
}
return max;
}
top() {
if (this.heap.length <= 1) {
return null
}
return this.heap[1]
}
empty() {
if (this.heap.length === 1) {
return true
}
return false
}
}
function main(input) {
const heap = new MaxHeap();
const result = [];
const N = input.shift();
input.map(Number).forEach(element => {
if (element === 0) {
result.push(heap.delete());
} else {
heap.insert(element)
}
});
console.log(result.join("\n"))
}