题目描述
三合一。描述如何只用一个数组来实现三个栈。
你应该实现push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum)方法。stackNum表示栈下标,value表示压入的值。
构造函数会传入一个stackSize参数,代表每个栈的大小。
示例1:
输入:
["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]
解题思路
这道题首先要把题目读懂,这里需要使用数组来实现3个栈的操作,查看三个方法,入参是stackNum,就是对应的每个栈:
push(stackNum, value)
pop(stackNum)
isEmpty(stackNum)
peek(stackNum)
这里有2种实现方式:
case1:使用一维数组
class TripleInOne1 {
Integer[] array;
int stackSize;
int[] indexArray;
public TripleInOne1(int stackSize) {
this.array = new Integer[3 * stackSize];
this.stackSize = stackSize;
this.indexArray = new int[3];
indexArray[0] = -1;
indexArray[1] = stackSize - 1;
indexArray[2] = 2 * stackSize - 1;
}
public void push(int stackNum, int value) {
if (indexArray[stackNum] + 1 < (stackNum + 1) * stackSize) {
array[++indexArray[stackNum]] = value;
}
}
public int pop(int stackNum) {
if (!isEmpty(stackNum)) {
int res = array[indexArray[stackNum]];
indexArray[stackNum]--;
return res;
}
return -1;
}
public int peek(int stackNum) {
if (!isEmpty(stackNum)) {
return array[indexArray[stackNum]];
}
return -1;
}
public boolean isEmpty(int stackNum) {
return indexArray[stackNum] == stackNum * stackSize - 1;
}
}
case2:使用二维数组
class TripleInOne {
Integer[][] array;
int[] indexArray;
public TripleInOne(int stackSize) {
this.array = new Integer[3][stackSize];
this.indexArray = new int[]{-1, -1, -1};
}
public void push(int stackNum, int value) {
if (indexArray[stackNum] + 1 < array[stackNum].length) {
array[stackNum][++indexArray[stackNum]] = value;
}
}
public int pop(int stackNum) {
if (!isEmpty(stackNum)) {
int res = array[stackNum][indexArray[stackNum]];
indexArray[stackNum]--;
return res;
}
return -1;
}
public int peek(int stackNum) {
if (!isEmpty(stackNum)) {
return array[stackNum][indexArray[stackNum]];
}
return -1;
}
public boolean isEmpty(int stackNum) {
return indexArray[stackNum] == -1;
}
//["TripleInOne", "push", "push", "push", "pop", "pop", "pop", "peek"]
//[[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]]
public static void main(String[] args) {
TripleInOne one = new TripleInOne(2);
one.push(0, 1);
one.push(0, 2);
one.push(0, 3);
one.pop(0);
one.pop(0);
one.pop(0);
one.peek(0);
}
}
总结
这道题是一道简单题,就是考查栈操作,这里我用了2种方式:一维数组和二维数组,从效率上讲使用二维数组更快。如果有更高效、简洁的方法,欢迎回复。