-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
74 lines (68 loc) · 1.52 KB
/
solution.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
var SortedStack = function () {
this.heap = [];
};
function swap (arr, i, j) {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
* @param {number} val
* @return {void}
*/
SortedStack.prototype.push = function (val) {
this.heap.push(val);
let index = this.heap.length - 1;
while (index > 0) {
const parent = (index - 1) >> 1;
if (this.heap[parent] > this.heap[index]) {
swap(this.heap, index, parent);
index = parent;
} else {
break;
}
}
};
/**
* @return {void}
*/
SortedStack.prototype.pop = function () {
this.heap[0] = this.heap[this.heap.length - 1];
this.heap.pop();
let index = 0;
while (2 * index + 1 < this.heap.length) {
let child = 2 * index + 1;
if (child + 1 < this.heap.length && this.heap[child + 1] < this.heap[child]) {
child++;
}
if (this.heap[index] > this.heap[child]) {
swap(this.heap, index, child);
index = child;
} else {
break;
}
}
};
/**
* @return {number}
*/
SortedStack.prototype.peek = function () {
if (this.heap.length === 0) {
return -1;
}
return this.heap[0];
};
/**
* @return {boolean}
*/
SortedStack.prototype.isEmpty = function () {
return this.heap.length === 0;
};
/**
* Your SortedStack object will be instantiated and called as such:
* var obj = new SortedStack()
* obj.push(val)
* obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.isEmpty()
*/