LeetCode面试题03.01

题目描述

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

你应该实现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]

实现思路

1.我们可以使用二维数组实现;

2.定义容量capacity,当初始化栈时,将capacity设为stackSize;

3.设置int型数组存储栈pop和push之后的下标,从而计算出栈是否已满。

代码实现

class TripleInOne {
    private int[][] threeStack;
    private int capacity;
    private int[] p = {0 ,0 ,0};
    public TripleInOne(int stackSize) {
        threeStack = new int[3][stackSize];
        capacity = stackSize;        
    }
    
    public void push(int stackNum, int value) {
        if(p[stackNum] < capacity){
            threeStack[stackNum][p[stackNum]] = value;
            p[stackNum]++;            
        }
    }
    
    public int pop(int stackNum) {
        int value = -1;
         if(p[stackNum] != 0){             
             p[stackNum]--;
             value = threeStack[stackNum][p[stackNum]];
             
         }
         return value;
    }
    
    public int peek(int stackNum) {
        int value = -1;
        if(p[stackNum] != 0){
            value = threeStack[stackNum][p[stackNum] - 1];
        }
        return value;
    }
    
    public boolean isEmpty(int stackNum) {
        if(p[stackNum] == 0){
            return true;
        }
        return false;
    }
}

/**
 * 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,java,javascript)