一、题目
三合一。描述如何只用一个数组来实现三个栈。
你应该实现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]
提示:
0 <= stackNum <= 2
二、C# 题解
很基础的题目,代码如下:
public class TripleInOne {
private int[][] stack; // 2 维数组存储 3 个栈
private int[] p; // 1 维数组存储 3 个栈的指针
public TripleInOne(int stackSize) {
stack = new int[3][];
for (int i = 0; i < 3; i++) {
stack[i] = new int[stackSize];
}
p = new int[] {-1, -1, -1};
}
public void Push(int stackNum, int value) {
if (p[stackNum] == stack[stackNum].Length - 1) return;
stack[stackNum][++p[stackNum]] = value;
}
public int Pop(int stackNum) {
if (p[stackNum] == -1) return -1;
return stack[stackNum][p[stackNum]--];
}
public int Peek(int stackNum) {
if (p[stackNum] == -1) return -1;
return stack[stackNum][p[stackNum]];
}
public bool IsEmpty(int stackNum) {
return p[stackNum] == -1;
}
}
/**
* 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);
* bool param_4 = obj.IsEmpty(stackNum);
*/
- 时间复杂度:无。
- 空间复杂度:无。