面试题 03.03. 堆盘子

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
56
57
58
59
60
61
class StackOfPlates {

private final List<Stack<Integer>> stackList;
private final int cap;
private int lastNotFullStackIndex;

public StackOfPlates(int cap) {
this.stackList = new ArrayList<>();
this.cap = cap;
this.lastNotFullStackIndex = -1;
}

public void push(int val) {
if (cap <= 0) {
return;
}

if (lastNotFullStackIndex == -1) {
stackList.add(new Stack<>());
lastNotFullStackIndex++;
}
Stack<Integer> stack = stackList.get(lastNotFullStackIndex);
if (stack.size() == cap) {
stackList.add(new Stack<>());
lastNotFullStackIndex++;
}

stackList.get(lastNotFullStackIndex).push(val);
}

public int pop() {
for (int i = stackList.size() - 1; i >= 0; i--) {
Stack<Integer> stack = stackList.get(i);
if (!stack.isEmpty()) {
int val = stack.pop();
if (stack.isEmpty()) {
lastNotFullStackIndex--;
}
return val;
}
}

return -1;
}

public int popAt(int index) {
for (int i = index; i < stackList.size(); i++) {
Stack<Integer> stack = stackList.get(i);
if (!stack.isEmpty()) {
int val = stack.pop();
if (stack.isEmpty()) {
lastNotFullStackIndex--;
}
return val;
}
}

return -1;
}

}

注意题目要求,之前的栈堆满盘子才能使用新的栈。

References

面试题 03.03. 堆盘子