728x90
https://leetcode.com/problems/implement-queue-using-stacks/
Implement Queue using Stacks - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
스택 2개 이용
class MyQueue:
def __init__(self):
self.input = []
self.output = []
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 = []
👉🏻스택은 맨 뒤의 아이템을 끄집어내야하므로 하나의 스택으로는 풀이가 불가능하다. 2개의 스택을 이용한다.
👉🏻pop()과 peek()은 결국 같은 데이터를 끄집어내는 것이므로 pop()할 때 peek()을 호출하고 재입력하도록 알고리즘을 구현한다.
✍🏻output의 값이 모두 pop()되기 전까지 다시 재입력이 일어나지 않으므로 분할 상환 분석에 따른 시간 복잡도는 여전히 O(1)이다.
728x90
'그 땐 Algorithm했지 > 그 땐 Python했지' 카테고리의 다른 글
[TAVE/이코테] ch04 구현 | 개념 정리 | 실전 문제 (0) | 2022.03.25 |
---|---|
[TAVE/이코테] ch03 그리디 | 개념 정리 | 실전 문제 (0) | 2022.03.22 |
[TAVE/파이썬 알고리즘] Ch10 | 데크, 우선순위 큐 - 개념 정리 (0) | 2022.03.08 |
[TAVE/파이썬 알고리즘 인터뷰] Ch12 | 그래프 - 개념 정리 (0) | 2022.03.04 |
[TAVE/파이썬 알고리즘] Ch8 | 연결 리스트 - 13번 팰린드롬 연결 리스트(leetcode 234) (0) | 2022.02.23 |