[BOJ] 28279: 덱 2

이슬비·2023년 11월 29일
0

Algorithm

목록 보기
108/110
post-thumbnail

Deque라는 자료구조를 알아보기 위한 문제인가 ...? queue랑 풀이가 비스무리한디요

1. 내 풀이: 성공

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

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

for _ in range(n):
    command = list(map(int, input().rstrip().split()))
    if command[0] == 1:
        dq.append(command[1])
    elif command[0] == 2:
        dq.appendleft(command[1])
    elif command[0] == 3:
        if len(dq) == 0:
            print(-1)
        else:
            print(dq.pop())
    elif command[0] == 4:
        if len(dq) == 0:
            print(-1)
        else:
            print(dq.popleft())
    elif command[0] == 5:
        print(len(dq))
    elif command[0] == 6:
        if len(dq) == 0:
            print(1)
        else:
            print(0)
    elif command[0] == 7:
        if len(dq) == 0:
            print(-1)
        else:
            print(dq[-1])
    else:
        if len(dq) == 0:
            print(-1)
        else:
            print(dq[0])

머 ... queue 풀 때랑 command가 string이 아니라는 것 빼고는 동일하다.

2. Deque

[POINT]

  • queue: FIFO = 선입선출 = 출입구가 단 한 개
  • deque: 양방향 queue

Deque의 경우, 스택처럼도, 큐처럼도 사용할 수 있다. 대신 시작점의 값을 넣고 빼거나, 끝점의 값을 넣고 빼는데 최적화된 연산 속도를 제공한다. 다시 말해, deque는 list의 상위옵션이랄까 ...

List를 사용한 풀이에서 시간 초과가 났다?
그럼 바로 Deque로 넘어가보자!

3. 느낀점

Deque에 대해서 예전에도 공부한 것 같은데 ㅋㅋ ...
앞으로는 까먹지말기!

profile
정말 알아?

0개의 댓글