【Leetcode解題】232. Implement Queue using Stacks
題目
- 題目連結
- 目標函式 :
isBalanced(root)- Input :
root: TreeNode - Output :
bool
- Input :
解題概念
- 題意 : 使用兩個 Stack 去實作 Queue的功能,須包含 :
push(x): 將x加入 Queue 尾端pop(): 刪除 Queue 最前端的元素並回傳peek(): 回傳 Queue 最前端的元素 (不須刪除)empty(): 回傳 Queue 是否為空
我的寫法
- 想法 : 此題在 Stack 與 Queue 範疇中也是經典的一題應用題,實作如下 :
- 宣告兩個 Stack
s與t - 實作四種功能 :
push(x): 將元素 Push 到 Stacks中即可peek(): 確認 Stackt是否為空 :- 若
t為空且s不為空,則對t一一執行pop(),並依序 Push 到t中 - 若
t為空且s也為空,代表 Queue 沒東西 - 否則直接對
t執行pop()即可
- 若
pop(): 先確認t是否可以進行pop(),否則取出s的第一個元素empty(): 若t為空且s也為空,代表 Queue 為空
- 宣告兩個 Stack
- 程式碼 :
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
42class MyQueue(object):
s = None
t = None
def __init__(self):
self.s = list()
self.t = list()
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.s.append(x)
def pop(self):
"""
:rtype: int
"""
if len(self.t) == 0:
while len(self.s) != 0:
self.t.append(self.s.pop())
return self.t.pop()
def peek(self):
"""
:rtype: int
"""
if len(self.t) != 0:
return self.t[len(self.t) - 1]
else:
return self.s[0]
def empty(self):
"""
:rtype: bool
"""
if len(self.s) == 0 and len(self.t) == 0:
return True
return False - 成效 :
- Time Complexity : $\color{DB4D6D}{O(1)}$ or $\color{DB4D6D}{O(n)}$
- Runtime: 15 ms (faster than 71.10%)
- Memory Usage: 13.3 MB (more than 69.11%)
解答 or 其他優秀寫法
- 想法 : 把我的寫法修得更加乾淨
push(x): 將元素 Push 到 Stacks中即可pop(): 先執行peek(),確認 Queue 有元素,同時把所有元素都移到 Stackt中,再取出s的第一個元素peek(): 確認 Stackt是否為空 :- 若
t為空,則對t一一執行pop(),並依序 Push 到t中 - 再回傳
t尾端的元素
- 若
empty(): 若t為空且s也為空,代表 Queue 為空
- 程式碼 :
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
38class MyQueue(object):
s = None
t = None
def __init__(self):
self.s = list()
self.t = list()
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.s.append(x)
def pop(self):
"""
:rtype: int
"""
self.peek()
return self.t.pop()
def peek(self):
"""
:rtype: int
"""
if not self.t:
while self.s:
self.t.append(self.s.pop())
return self.t[-1]
def empty(self):
"""
:rtype: bool
"""
return not self.s and not self.t - 成效 :
- Time Complexity : $\color{DB4D6D}{O(1)}$ or $\color{DB4D6D}{O(n)}$
- Runtime: 13 ms (faster than 81.29%)
- Memory Usage: 13.4 MB (more than 69.11%)
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Robin's Tech Blog!


