题目描述:
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例:
输入:
[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
思路: 先 “先入先出”在把这些出来的压栈到另一个就是正常队列顺序
用两个栈,采用负负为正的思想,使用栈left和栈right,每次有数据来压栈left,取栈头的时候,先看right栈是否有,有取顶,没有的话,把左边的压栈right再取顶。peek是和pop一样的,就是需要把删除的再补回来。
代码
class MyQueue(object):
def __init__(self):
self.left = []
self.right = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.left.append(x)
def pop(self):
"""
:rtype: int
"""
if self.right:
return self.right.pop()
else:
while self.left:
self.right.append(self.left.pop())
return self.right.pop()
def peek(self):
"""
:rtype: int
"""
if self.right:
result = self.right.pop()
self.right.append(result)
return result
else:
while self.left:
self.right.append(self.left.pop())
result = self.right.pop()
self.right.append(result)
return result
def empty(self):
"""
:rtype: bool
"""
if not self.left and not self.right:
return True
else:
return False
官方给的另一个思路:
https://leetcode-cn.com/problems/implement-queue-using-stacks/solution/yong-zhan-shi-xian-dui-lie-by-leetcode/
对应链接
始终有一个栈 l 维持与队列的样子相同,在每次push一个元素的时候,进行调整,把l 中所有的都放到r中,在l中压入新元素x,再把其他的元素从r中拿出来压入l,这样L中就始终保持和队列的样子是一致的。
官方思想的第二种就是本片所说的第一个思路。
第一种思路的时间复杂度,push pop peek都是O(1),摊还分析的话。
摊还分析:
摊还分析给出了所有操作的平均性能。摊还分析的核心在于,最坏情况下的操作一旦发生了一次,那么在未来很长一段时间都不会再次发生,这样就会均摊每次操作的代价。