-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmin-stack.js
More file actions
35 lines (31 loc) · 711 Bytes
/
min-stack.js
File metadata and controls
35 lines (31 loc) · 711 Bytes
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
class MinStack {
constructor() {
this.elements = [];
this.mins = [];
this.min = undefined;
}
push(element) {
this.elements.push(element);
if (element < this.min || this.min === undefined) {
this.min = element;
this.mins.push(element);
}
}
pop() {
if (this.elements.length > 0) {
const elementToPop = this.elements.pop();
if (elementToPop === this.min) {
this.mins.pop();
this.min = this.mins[this.mins.length - 1];
}
return elementToPop;
}
}
}
const myMinStack = new MinStack();
myMinStack.push(3);
myMinStack.push(4);
myMinStack.push(5);
myMinStack.push(1);
myMinStack.push(-100);
console.log(myMinStack.min);