题目链接
三合一
题目描述
注意点
- 0 <= stackNum <= 2
解答思路
- 可以使用一个一维数组存储三个栈的元素,其中idx存储的是第一个数组中的元素,idx + 1存储的是第二个数组中的元素,idx + 2存储的是第三个数组中的元素,所以除了创建数组arr外,还要使用idxs存储每个栈中最后一个元素的位置(方便插入和弹出时找到相应位置)
代码
class TripleInOne {
public static final int N = 3;
int[] arr;
int[] idxs;
int size;
public TripleInOne(int stackSize) {
size = stackSize * N;
arr = new int[size];
idxs = new int[N];
idxs[0] = -3;
idxs[1] = -2;
idxs[2] = -1;
}
public void push(int stackNum, int value) {
if (idxs[stackNum] + 3 >= size) {
return;
}
idxs[stackNum] += 3;
arr[idxs[stackNum]] = value;
}
public int pop(int stackNum) {
if (idxs[stackNum] < 0) {
return -1;
}
int res = arr[idxs[stackNum]];
idxs[stackNum] -= 3;
return res;
}
public int peek(int stackNum) {
return idxs[stackNum] < 0 ? -1 : arr[idxs[stackNum]];
}
public boolean isEmpty(int stackNum) {
return idxs[stackNum] < 0;
}
}
/**
* 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);
*/
关键点
- 当栈满时
push
不压入元素 - 当栈为空时
pop, peek
返回-1