본문 바로가기

STUDY/Python

[백준] 18258번 큐2 python

728x90

이 문제는 큐 문제이다.

 

이 문제의 꿀팁

1. import sys를 사용하여 입력을 받는다.

2. from collections import deque를 사용하여 문제를 푼다.

 

위 꿀팁을 꼭 써야 시간 초과가 나지 않는다.

 

[나의 풀이 1 - 시간 초과]

import sys

len_element = int(sys.stdin.readline())
box = []

for i in range(len_element):
  command = sys.stdin.readline()
  if command.find('push')!= -1:
    command = command.replace('push ', '')
    box.append(int(command))

  elif command.find('pop')!= -1:
    if len(box) !=0:
      print(box[0])
      del box[0]
    else: 
      print(-1)

  elif command.find('size')!= -1:
    print(len(box))

  elif command.find('empty')!= -1:
    if len(box) != 0:
      print(0)
    else :
      print(1)

  elif command.find('front')!= -1:
    if len(box)!=0:
      print(box[0])
    else:
      print(-1)

  elif command.find('back')!= -1:
    if len(box) != 0:
      print(box[-1])
    else:
      print(-1)

 

[나의 풀이 2 - 통과한 풀이]

from collections import deque
import sys

len_element = int(sys.stdin.readline())
box = deque()

for i in range(len_element):
  command = sys.stdin.readline()
  if command.find('push')!= -1:
    command = command.replace('push ', '')
    box.append(int(command))

  elif command.find('pop')!= -1:
    if len(box) !=0:
      print(box[0])
      box.popleft() 
    else: 
      print(-1)

  elif command.find('size')!= -1:
    print(len(box))

  elif command.find('empty')!= -1:
    if len(box) != 0:
      print(0)
    else :
      print(1)

  elif command.find('front')!= -1:
    if len(box)!=0:
      print(box[0])
    else:
      print(-1)

  elif command.find('back')!= -1:
    if len(box) != 0:
      print(box[-1])
    else:
      print(-1)

728x90

'STUDY > Python' 카테고리의 다른 글

[Softeer] GBC python  (0) 2023.06.25
[Softeer] 바이러스 python  (0) 2023.06.25
[백준] 9012번 괄호 python  (0) 2023.06.19
[백준] 10828번 스택 python  (0) 2023.06.19
[자료구조] 스택 stack  (0) 2023.06.19