-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path155.min-stack.ts
51 lines (45 loc) · 996 Bytes
/
155.min-stack.ts
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
/*
* @lc app=leetcode id=155 lang=typescript
*
* [155] Min Stack
*/
// @lc code=start
class MinStack {
#stack = [];
#minIndex = 0;
constructor() {
this.#stack = [];
}
push(x: number): void {
this.#stack[this.#stack.length] = x;
if (x < this.#stack[this.#minIndex])
this.#minIndex = this.#stack.length - 1;
}
pop(): void {
if (this.#stack.length <= 1) this.#stack = [];
this.#stack.splice(this.#stack.length - 1, 1);
if (this.#minIndex === this.#stack.length) {
this.#minIndex = 0;
for (let i = 0; i < this.#stack.length; i++) {
if (this.#stack[this.#minIndex] > this.#stack[i]) {
this.#minIndex = i;
}
}
}
}
top(): number {
return this.#stack[this.#stack.length - 1];
}
getMin(): number {
return this.#stack[this.#minIndex];
}
}
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/
// @lc code=end