leetcode-232

232. 用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

进阶:

  • 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

题解

解法一

当主栈元素数量大于1时,全部出栈,将其加入到辅助栈中,然后将当前元素添加到主栈,然后再将辅助栈的元素全部入到主栈中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.master = list()
self.aux = list()
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
if len(self.master) == 0:
self.master.append(x) # 入栈
else:
while self.master:
temp = self.master.pop()
self.aux.append(temp)
self.master.append(x)
while self.aux:
temp = self.aux.pop()
self.master.append(temp)

def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
return self.master.pop()

def peek(self) -> int:
"""
Get the front element.
"""
return self.master[-1]

def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return True if len(self.master) == 0 else False

解法二:官方题解

将一个栈当作输入栈,用于压入 $push$ 传入的数据;另一个栈当作输出栈,用于 $pop$ 和 $peek$ 操作。

每次 $pop$ 或 $peek$ 时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。

这个只需要倒一次。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.master = list()
self.aux = list()


def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.master.append(x)

def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if len(self.aux) != 0:
return self.aux.pop()
else:
while self.master:
temp = self.master.pop()
self.aux.append(temp)
return self.aux.pop()

def peek(self) -> int:
"""
Get the front element.
"""
if len(self.aux) != 0:
return self.aux[-1]
else:
while self.master:
temp = self.master.pop()
self.aux.append(temp)
return self.aux[-1]

def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return True if len(self.master)+len(self.aux) == 0 else False

作者

bd160jbgm

发布于

2021-05-30

更新于

2021-05-30

许可协议