728x90
풀이 1
바로 옆 문제인 스택과 같이 빈 배열을 만들어 pop을 시켰다. pop(0)이라 오래 걸릴 줄 알았는데 생각보다 빠르다.
# 76ms / 29380KB
from sys import stdin
Q = []
def queue(i):
cmd = i[0]
if cmd == "push":
Q.append(int(i[1]))
if cmd == "pop":
if Q:
return Q.pop(0)
else:
return -1
if cmd == "size":
return len(Q)
if cmd == "front":
if Q:
return Q[0]
else:
return -1
if cmd == "back":
if Q:
return Q[-1]
else:
return -1
if cmd == "empty":
return 0 if Q else 1
n = int(input())
result = []
for i in range(n):
res = queue(list(map(str, stdin.readline().split())))
if res != None:
result.append(res)
for i in result:
print(i)
풀이 2. deque를 사용한 풀이
오잉? 더 오래 걸린다. 왜 pop(0)을 사용한 코드가 더 빠른 것일까...?
만약 인풋이 더 많다면 데큐가 더 효율적이려나? 기억해 두었다가 비교해 봐야겠다.
# 100ms / 31824KB
from sys import stdin
from collections import deque
Q = deque()
def queue(i):
cmd = i[0]
if cmd == "push":
Q.append(int(i[1]))
if cmd == "pop":
if Q:
return Q.popleft()
else:
return -1
if cmd == "size":
return len(Q)
if cmd == "front":
if Q:
return Q[0]
else:
return -1
if cmd == "back":
if Q:
return Q[-1]
else:
return -1
if cmd == "empty":
return 0 if Q else 1
n = int(input())
result = []
for i in range(n):
res = queue(list(map(str, stdin.readline().split())))
if res != None:
result.append(res)
for i in result:
print(i)
'PS > Python' 카테고리의 다른 글
[BOJ / Java] 1920 - 수 찾기 (0) | 2020.08.20 |
---|---|
[BOJ/Python] 1158 - 요세푸스 문제 (0) | 2020.07.21 |
[BOJ/Python] 10828 - 스택 (0) | 2020.07.07 |
[BOJ/Python] 10815 - 숫자 카드 (0) | 2020.07.07 |
[BOJ/Python] 10989 - 수 정렬하기 3 (0) | 2020.07.07 |
최근댓글