LeetCode—Interview Questions: Three in One (Array)

Three in one (simple)

October 14, 2020

Question source: Likou

Insert picture description here

Problem Solving The
meaning of the question is this. Use an array to store the contents of the three stacks. StackNum represents which stack is. StackSize is the size of each stack. This also determines the size of our array as stackSize*3

class TripleInOne {
    
    
    private int[] arr;  //装栈数据的数组
    private int stackSize;  //栈的容量
    private int[] stackTop;     //三个栈的栈顶指针
    public TripleInOne(int stackSize) {
    
    
        this.stackSize=stackSize;
        arr=new int[stackSize*3];
        stackTop=new int[]{
    
    0,1,2};
    }
    
    public void push(int stackNum, int value) {
    
    
        //获得当前栈顶的元素
        int curStackTop=stackTop[stackNum];
        //如果当前栈顶除以3等于栈的大小,代表满了,压不进去
        if(curStackTop/3==stackSize) return;
        //压进数组,栈顶指针加3
        arr[curStackTop]=value;
        stackTop[stackNum]+=3;
    }
    
    public int pop(int stackNum) {
    
    
        if(isEmpty(stackNum)) return -1;
        //删除对应的栈顶元素,前面加入元素的时候加了3,现在要减掉
        int value = arr[stackTop[stackNum] - 3];
        //栈顶下标减小3
        stackTop[stackNum] -= 3;
        return value;
    }
    
    public int peek(int stackNum) {
    
    
        if(isEmpty(stackNum)) return -1;
        return arr[stackTop[stackNum]-3];
    }
    
    public boolean isEmpty(int stackNum) {
    
    
        //如果小于3,说明没数据了
        return stackTop[stackNum] < 3;  
    }
}

/**
 * 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);
 */

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41541562/article/details/109075928