-
Notifications
You must be signed in to change notification settings - Fork 42
/
solution.ts
55 lines (47 loc) · 1.25 KB
/
solution.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
52
53
54
55
class MaxStack {
stack1:number[] = [];
stack2:number[] = [];
constructor () {
}
push (x: number): void {
this.stack1.push(x);
if (this.stack2.length === 0 || x >= this.stack2[this.stack2.length - 1]) {
this.stack2.push(x);
} else {
this.stack2.push(this.stack2[this.stack2.length - 1]);
}
}
pop (): number {
this.stack2.pop();
return this.stack1.pop();
}
top (): number {
return this.stack1[this.stack1.length - 1];
}
peekMax (): number {
return this.stack2[this.stack2.length - 1];
}
popMax (): number {
const result = this.stack2[this.stack2.length - 1];
const tmp:number[] = [];
while (this.stack1[this.stack1.length - 1] !== result) {
this.stack2.pop();
tmp.push(this.stack1.pop());
}
this.stack1.pop();
this.stack2.pop();
while (tmp.length) {
this.push(tmp.pop());
}
return result;
}
}
/**
* Your MaxStack object will be instantiated and called as such:
* var obj = new MaxStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.peekMax()
* var param_5 = obj.popMax()
*/