英文原文
Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks
that mimics this. SetOfStacks
should be composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks.push()
and SetOfStacks.pop()
should behave identically to a single stack (that is, pop()
should return the same values as it would if there were just a single stack). Follow Up: Implement a function popAt(int index)
which performs a pop operation on a specific sub-stack.
You should delete the sub-stack when it becomes empty. pop
, popAt
should return -1 when there's no element to pop.
Example1:
Input: ["StackOfPlates", "push", "push", "popAt", "pop", "pop"] [[1], [1], [2], [1], [], []] Output: [null, null, null, 2, 1, -1] Explanation:
Example2:
Input: ["StackOfPlates", "push", "push", "push", "popAt", "popAt", "popAt"] [[2], [1], [2], [3], [0], [0], [0]] Output: [null, null, null, null, 2, 1, 3]
中文题目
堆盘子。设想有一堆盘子,堆太高可能会倒下来。因此,在现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请实现数据结构SetOfStacks
,模拟这种行为。SetOfStacks
应该由多个栈组成,并且在前一个栈填满时新建一个栈。此外,SetOfStacks.push()
和SetOfStacks.pop()
应该与普通栈的操作方法相同(也就是说,pop()返回的值,应该跟只有一个栈时的情况一样)。 进阶:实现一个popAt(int index)
方法,根据指定的子栈,执行pop操作。
当某个栈为空时,应当删除该栈。当栈中没有元素或不存在该栈时,pop
,popAt
应返回 -1.
示例1:
输入: ["StackOfPlates", "push", "push", "popAt", "pop", "pop"] [[1], [1], [2], [1], [], []] 输出: [null, null, null, 2, 1, -1]
示例2:
输入: ["StackOfPlates", "push", "push", "push", "popAt", "popAt", "popAt"] [[2], [1], [2], [3], [0], [0], [0]] 输出: [null, null, null, null, 2, 1, 3]
通过代码
高赞题解
思路
- 新建一个List<Stack
>用来存放各个栈,而且栈的个数是动态变化的。 - push的时候,可能需要新建一个栈,或者直接插入到最后一个栈中。
- pop直接调用popAt方法。其中popAt方法需要处理的是弹出指定位置栈的栈顶元素。我们可以通过list拿到指定index的栈,拿到之后执行stack的pop操作即可。同时如果弹出栈顶元素之后,当前stack变成空了,需要将当前stack从list中移除。
class StackOfPlates {
private List<Stack<Integer>> stackList;
private int cap;
public StackOfPlates(int cap) {
stackList = new ArrayList<>();
this.cap = cap;
}
public void push(int val) {
if (cap <= 0) {
return;
}
if (stackList.isEmpty() || stackList.get(stackList.size() - 1).size() == cap) {
Stack<Integer> stack = new Stack<>();
stack.push(val);
stackList.add(stack);
return;
}
stackList.get(stackList.size() - 1).push(val);
}
public int pop() {
return popAt(stackList.size() - 1);
}
public int popAt(int index) {
if (index < 0 || index >= stackList.size()) {
return -1;
}
Stack<Integer> stack = stackList.get(index);
if (stack.isEmpty()) {
return -1;
}
int res = stack.pop();
if (stack.isEmpty()) {
stackList.remove(index);
}
return res;
}
}
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
9045 | 23349 | 38.7% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|