gold-3-3


堆盘子。设想有一堆盘子,堆太高可能会倒下来。因此,在现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请实现数据结构SetOfStacks,模拟这种行为。SetOfStacks应该由多个栈组成,并且在前一个栈填满时新建一个栈。此外,SetOfStacks.push()SetOfStacks.pop()应该与普通栈的操作方法相同(也就是说,pop()返回的值,应该跟只有一个栈时的情况一样)。 进阶:实现一个popAt(int index)方法,根据指定的子栈,执行pop操作。

当某个栈为空时,应当删除该栈。当栈中没有元素或不存在该栈时,poppopAt 应返回 -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]

//leetcode submit region begin(Prohibit modification and deletion)
class StackOfPlates {
    private int cap;
    private List<List<Integer>> stackList;

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

    public void push(int val) {
        if (this.cap <= 0) {
            return;
        }
        if (stackList.isEmpty() || stackList.get(stackList.size() - 1).size() == this.cap) {
            List<Integer> newStack = new ArrayList<>();
            newStack.add(val);
            stackList.add(newStack);
        } else {
            stackList.get(stackList.size() - 1).add(val);
        }
    }

    public int pop() {
        if (this.cap <= 0) {
            return -1;
        }
        for (int i = stackList.size() - 1; i >= 0; i--) {
            if (!stackList.get(i).isEmpty()) {
                int value = stackList.get(i).get(stackList.get(i).size() - 1);
                stackList.get(i).remove(stackList.get(i).size() - 1);
                if (stackList.get(i).isEmpty()) {
                    stackList.remove(i);
                }
                return value;
            }
        }

        return -1;
    }

    public int popAt(int index) {
        if (this.cap <= 0) {
            return -1;
        }
        if (index >= this.stackList.size()) {
            return -1;
        }

        if (!stackList.get(index).isEmpty()) {
            int value = stackList.get(index).get(stackList.get(index).size() - 1);
            stackList.get(index).remove(stackList.get(index).size() - 1);

            if (stackList.get(index).isEmpty()) {
                stackList.remove(index);
            }
            return value;
        }

        return -1;
    }
}
/**
 * Your StackOfPlates object will be instantiated and called as such:
 * StackOfPlates obj = new StackOfPlates(cap);
 * obj.push(val);
 * int param_2 = obj.pop();
 * int param_3 = obj.popAt(index);
 */
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !