-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminStack.ts
More file actions
47 lines (41 loc) · 989 Bytes
/
Copy pathminStack.ts
File metadata and controls
47 lines (41 loc) · 989 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
36
37
38
39
40
41
42
43
44
45
46
47
class MinStack {
stack: Array<number>;
minNumberStack: Array<number>;
minNumber: number;
constructor() {
this.stack = [];
this.minNumberStack = [];
this.minNumber = Number.MAX_SAFE_INTEGER;
}
push(val: number): void {
this.stack.push(val);
if (this.minNumber >= val) {
this.minNumber = val;
this.minNumberStack.push(this.minNumber);
}
}
pop(): void {
const removedNumber = this.stack.pop();
if (this.minNumber === removedNumber) {
this.minNumberStack.pop();
this.minNumber =
this.minNumberStack.length > 0
? this.minNumberStack[this.minNumberStack.length - 1]
: Number.MAX_SAFE_INTEGER;
}
}
top(): number {
return this.stack[this.stack.length - 1];
}
getMin(): number {
return this.minNumberStack[this.minNumberStack.length - 1];
}
}
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(val)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/