forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
55 lines (50 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 StackOfPlates {
private cap: number;
private stacks: number[][];
constructor(cap: number) {
this.cap = cap;
this.stacks = [];
}
push(val: number): void {
if (this.cap === 0) {
return;
}
const n = this.stacks.length;
const stack = this.stacks[n - 1];
if (stack == null || stack.length === this.cap) {
this.stacks.push([val]);
} else {
stack.push(val);
}
}
pop(): number {
const n = this.stacks.length;
if (n === 0) {
return -1;
}
const stack = this.stacks[n - 1];
const res = stack.pop();
if (stack.length === 0) {
this.stacks.pop();
}
return res;
}
popAt(index: number): number {
if (index >= this.stacks.length) {
return -1;
}
const stack = this.stacks[index];
const res = stack.pop();
if (stack.length === 0) {
this.stacks.splice(index, 1);
}
return res;
}
}
/**
* Your StackOfPlates object will be instantiated and called as such:
* var obj = new StackOfPlates(cap)
* obj.push(val)
* var param_2 = obj.pop()
* var param_3 = obj.popAt(index)
*/