| 用一个数组实现三个栈
三合一。描述如何只用一个数组来实现三个栈。
你应该实现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]
| 题解
class TripleInOne:
def __init__(self, stackSize: int):
self.stack = [0 for i in range(stackSize * 3)]
self.ptr1 = 0
self.ptr2 = 0 + stackSize
self.ptr3 = 0 + 2 * stackSize
self.stackSize = stackSize
def push(self, stackNum: int, value: int) -> None:
if stackNum == 0 and 0 <= self.ptr1 < self.stackSize:
self.stack[self.ptr1] = value
self.ptr1 += 1
elif stackNum == 1 and self.stackSize <= self.ptr2 < 2 * self.stackSize:
self.stack[self.ptr2] = value
self.ptr2 += 1
elif stackNum == 2 and 2 * self.stackSize <= self.ptr3 < 3 * self.stackSize:
self.stack[self.ptr3] = value
self.ptr3 += 1
def pop(self, stackNum: int) -> int:
if stackNum == 0 and 0 < self.ptr1 <= self.stackSize:
self.ptr1 -= 1
return self.stack[self.ptr1]
elif stackNum == 1 and self.stackSize < self.ptr2 <= 2 * self.stackSize:
self.ptr2 -= 1
return self.stack[self.ptr2]
elif stackNum == 2 and 2 * self.stackSize < self.ptr3 <= 3 * self.stackSize:
self.ptr3 -= 1
return self.stack[self.ptr3]
return -1
def peek(self, stackNum: int) -> int:
if stackNum == 0 and 0 < self.ptr1 <= self.stackSize:
return self.stack[self.ptr1-1]
elif stackNum == 1 and self.stackSize < self.ptr2 <= 2 * self.stackSize:
return self.stack[self.ptr2-1]
elif stackNum == 2 and 2 * self.stackSize < self.ptr3 <= 3 * self.stackSize:
return self.stack[self.ptr3-1]
return -1
def isEmpty(self, stackNum: int) -> bool:
if stackNum == 0 and self.ptr1 == 0:
return True
elif stackNum == 1 and self.ptr2 == 0 + self.stackSize:
return True
elif stackNum == 2 and self.ptr3 == 0 + 2 * self.stackSize:
return True
return False