https://leetcode.com/problems/implement-queue-using-stacks/
스택을 두 개 사용해서 큐를 구현하는 문제
나의 풀이
class MyQueue:
def __init__(self):
self.s1 = list()
self.s2 = list()
def push(self, x: int) -> None:
self.s1.append(x)
def pop(self) -> int:
if self.s2:
return self.s2.pop()
while self.s1:
self.s2.append(self.s1.pop())
return self.s2.pop()
def peek(self) -> int:
if self.s2:
return self.s2[-1]
elif self.s1:
return self.s1[0]
else:
return None
def empty(self) -> bool:
return len(self.s1) == 0 and len(self.s2) == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
틀린 풀이는 아닌데, peek와 pop에서 단정하지 못한 느낌이 난다.
깔끔한 풀이
class MyQueue:
def __init__(self):
self.input = list()
self.output = list()
def push(self, x: int) -> None:
self.input.append(x)
def pop(self) -> int:
self.peek()
return self.output.pop()
def peek(self) -> int:
if not self.output:
while self.input:
self.output.append(self.input.pop())
return self.output[-1]
def empty(self) -> bool:
return self.input == [] and self.output == []
'Programming > LeetCode' 카테고리의 다른 글
[LeetCode] Search a 2D Matrix (0) | 2022.03.30 |
---|---|
[LeetCode] Design Circular Queue (스택으로 원형 큐 구현) (0) | 2022.03.29 |
[LeetCode] Implement Stack using Queues(큐로 스택 구현) (0) | 2022.03.29 |
[LeetCode] Daily Temperatures (0) | 2022.03.29 |
[LeetCode] Remove Duplicate Letters (0) | 2022.03.29 |
댓글