백준 / 실버4 / 18258 큐 2 / Python [시간복잡도]

jjin·2023년 10월 19일
0

https://www.acmicpc.net/problem/18258

첫 풀이

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

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

for i in range(n):
    c = input().split()
    if c[0] == 'push':
        d.append(c[1])
    elif c[0] == 'pop':
        p = -1 if len(d) == 0 else d.popleft()
        print(p)
    elif c[0] == 'size':
        print(len(d))
    elif c[0] == 'empty':
        p = 1 if len(d) == 0 else 0
        print(p)
    elif c[0] == 'front':
        p = -1 if len(d) == 0 else d[0]
        print(p)
    else:
        p = -1 if len(d) == 0 else d[-1]
        print(p)

처음 시간 초과

c = [input().split() for _ in range(n)]
써서 배열에 저장해두고 쓰려고했는데 시간 초과

개선한 풀이

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

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

for i in range(n):
    c = input().split()
    if c[0] == 'push':
        d.append(c[1])
       	continue
    elif c[0] == 'size':
        p = len(d)
    elif c[0] == 'pop':
        p = -1 if len(d) == 0 else d.popleft()
    elif c[0] == 'empty':
        p = 1 if len(d) == 0 else 0
    elif c[0] == 'front':
        p = -1 if len(d) == 0 else d[0]
    else:
        p = -1 if len(d) == 0 else d[-1]
    print(p)
profile
진짜

0개의 댓글