반응형
# Problem
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class:
Notes:
Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer. Constraints:
|
# My Answer
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.s = []
self.q=[]
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.q=[]
if self.s ==[]: # s가 비어있으면 그냥 s에 추가
self.s.append(x)
else: # 이미 s에 값이 있으면, s 앞에 값을 추가
self.q.append(x)
self.s = self.q+self.s
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
a = self.s.pop()
return a
def peek(self) -> int:
"""
Get the front element.
"""
return self.s[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return len(self.s)==0
# Solution 1 - 스택 2개 사용
class MyQueue:
def __init__(self):
self.input = []
self.output = []
def push(self, x):
self.input.append(x)
def pop(self):
self.peek()
return self.output.pop()
def peek(self):
# output이 없으면 모두 재입력 #output에 값이 있으면 output에서 먼저 들어온 값 반환
if not self.output:
while self.input:
self.output.append(self.input.pop())
return self.output[-1]
def empty(self):
return self.input == [] and self.output == []
반응형
'Algorithm > LEET CODE ( 파이썬 알고리즘 인터뷰)' 카테고리의 다른 글
[LEET CODE] 739. Daily Temperatures (0) | 2021.03.29 |
---|---|
[LEET CODE] 622. Design Circular Queue (0) | 2021.03.29 |
[LEET CODE] 225. Implement Stack using Queues (0) | 2021.03.26 |
❗️[LEET CODE] 316. Remove Duplicate Letters (0) | 2021.03.23 |
[LEET CODE] 20. Valid Parentheses (0) | 2021.03.23 |