程序员面试金典-面试题 03.01. 三合一

人盡茶涼 提交于 2020-03-04 17:59:00

题目:

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

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

分析:

开辟数组的大小为stackNum*3+3,平分数组作为三个栈存储的空间,额外再给三个位置用来记录每个栈存储元素的个数,就用,数组中最后三个索引,array[size- 0]表示第一个栈,array[size- 1]表示第二个栈,array[size- 2]表示第三个栈,正好对应每个栈的序号。

程序:

class TripleInOne {

    public TripleInOne(int stackSize) {
        stack = new int[stackSize * 3 + 3];
    }
    
    public void push(int stackNum, int value) {
        int size = stack.length - 3;
        if(stack[stack.length - stackNum - 1] >= (size / 3))
            return;
        int index = stackNum * (size / 3);
        stack[index + stack[stack.length - stackNum - 1]] = value;
        stack[stack.length - stackNum - 1]++;
    }
    
    public int pop(int stackNum) {
        int size = stack.length - 3;
        if(stack[stack.length - stackNum - 1] <= 0)
            return -1;
        int index = stackNum * (size / 3) + stack[stack.length - stackNum - 1] - 1;
        int res = stack[index];
        stack[stack.length - stackNum - 1]--;
        return res;
    }
    
    public int peek(int stackNum) {
        int size = stack.length - 3;
        if(isEmpty(stackNum))
            return -1;
        int index = stackNum * (size / 3) + stack[stack.length - stackNum - 1] - 1;
        int res = stack[index];
        return res;
    }
    
    public boolean isEmpty(int stackNum) {
        return stack[stack.length - stackNum - 1] == 0;
    }
    private int[] stack;
}

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!