Article Directory
1. Topic
triple. Describe how to implement three stacks using only one array.
You should implement push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum)
method. stackNum
Represents the stack subscript, value
representing the pushed value.
The constructor will pass in a stackSize
parameter representing the size of each stack.
Click here to jump to the topic .
Example 1:
Input:
["TripleInOne", "push", "push", "pop", "pop", "pop", "isEmpty"] [[1], [0,
1], [0, 2], [0 ], [0], [0], [0]]
Output:
[null, null, null, 1, -1, -1, true]
Explanation: return -1 when the stack is empty , and not presspop, peek
when the stack is fullpush
into the element.
Example 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]
hint:
0 <= stackNum <= 2
2. C# solution
Very basic topic, the code is as follows:
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);
*/
- Time Complexity: None.
- Space Complexity: None.