18258(큐2) - 자료구조(큐)

지환·2023년 10월 14일
0

백준(python)

목록 보기
58/67
post-thumbnail

출처 | https://www.acmicpc.net/problem/18258

코드

import sys 
from collections import deque
input = sys.stdin.readline


n = int(input())
queue = deque([])

for i in range(n):
    command = input().split()

    if command[0] == "push":
        queue.append(command[1])
    
    if command[0] == "pop":
        if len(queue) > 0:
            print(queue.popleft())
        else:
            print(-1)
    
    if command[0] == "size":
        print(len(queue))
    
    if command[0] == "empty":
        if len(queue) == 0:
            print(1)
        else:
            print(0)
    if command[0] == "front":
        if len(queue) > 0:
            print(queue[0])
        else:
            print(-1)

    if command[0] == "back":
        if len(queue) > 0:
            print(queue[-1])
        else:
            print(-1)

  • 리스트로 선언해서 pop(0)를 하게 되면, 첫 번째 요소를 pop 하고나서 나머지 요소들의 인덱스를 1칸씩 당기는 과정에서 O(n)의 계산량이 발생하기 때문에 deque를 이용해서 시간초과 문제를 해결하면 된다.
profile
아는만큼보인다.

0개의 댓글