gold-3-1


三合一。描述如何只用一个数组来实现三个栈。

你应该实现push(stackNum, value)pop(stackNum)isEmpty(stackNum)peek(stackNum)方法。stackNum表示栈下标,value表示压入的值。

构造函数会传入一个stackSize参数,代表每个栈的大小。

示例1:

 输入:
["TripleInOne", "push", "push", "pop", "pop", "pop", "isEmpty"]
[[1], [0, 1], [0, 2], [0], [0], [0], [0]]
 输出:
[null, null, null, 1, -1, -1, true]
说明:当栈为空时`pop, peek`返回-1,当栈满时`push`不压入元素。

示例2:

 输入:
["TripleInOne", "push", "push", "push", "pop", "pop", "pop", "peek"]
[[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]]
 输出:
[null, null, null, null, 2, 1, -1, -1]

提示:

  • 0 <= stackNum <= 2

//leetcode submit region begin(Prohibit modification and deletion)
class TripleInOne {

    private int[] valueArr;

    private int[] indexArr;

    private int stackSize;

    public TripleInOne(int stackSize) {
        this.valueArr = new int[stackSize * 3];
        this.indexArr = new int[3];
        this.indexArr[0] = -1;
        this.indexArr[1] = -1;
        this.indexArr[2] = -1;
        this.stackSize = stackSize;
    }

    public void push(int stackNum, int value) {
        if (this.indexArr[stackNum] == stackSize - 1) {
            return;
        }
        this.indexArr[stackNum]++;
        this.valueArr[this.indexArr[stackNum] * 3 + stackNum] = value;
    }

    public int pop(int stackNum) {
        if (this.indexArr[stackNum] == -1) {
            return -1;
        }
        int value = this.valueArr[this.indexArr[stackNum] * 3 + stackNum];
        this.indexArr[stackNum]--;
        return value;
    }

    public int peek(int stackNum) {
        if (this.indexArr[stackNum] == -1) {
            return -1;
        }
        return this.valueArr[this.indexArr[stackNum] * 3 + stackNum];
    }

    public boolean isEmpty(int stackNum) {
        return this.indexArr[stackNum] == -1;
    }
}

/**
 * Your TripleInOne object will be instantiated and called as such:
 * TripleInOne obj = new TripleInOne(stackSize);
 * obj.push(stackNum,value);
 * int param_2 = obj.pop(stackNum);
 * int param_3 = obj.peek(stackNum);
 * boolean param_4 = obj.isEmpty(stackNum);
 */
//leetcode submit region end(Prohibit modification and deletion)

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