티스토리 뷰
728x90
반응형
https://www.acmicpc.net/problem/18258
18258번: 큐 2
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
리스트로 해서 풀었더니 시간 초과가 나왔다.
pop(0) 을 하면 내부에서 앞으로 당기는 것 때문에 O(n)이 되어 그런 것 같았다.
그래서 deque를 사용했더니 통과했다.
시도 1 - [ ] 사용, 시간초과
n=int(input())
queue=[]
for i in range(n):
line = input()
if "push" in line:
a,num=line.split()
queue.append(num)
elif line=="pop":
if queue:
print(queue.pop(0))
else:
print(-1)
elif line=="size":
print(len(queue))
elif line=="front":
if queue:
print(queue[0])
else:
print(-1)
elif line=="back":
if queue:
print(queue[-1])
else:
print(-1)
elif line=="empty":
if queue:
print(0)
else:
print(1)
시도 2 - deque 사용 , 통과
import sys
from collections import deque
n=int(sys.stdin.readline())
queue=deque()
for i in range(n):
line = sys.stdin.readline().strip()
if "push" in line:
a,num=line.split()
queue.append(num)
elif line=="pop":
if queue:
print(queue.popleft())
else:
print(-1)
elif line=="size":
print(len(queue))
elif line=="front":
if queue:
print(queue[0])
else:
print(-1)
elif line=="back":
if queue:
print(queue[-1])
else:
print(-1)
elif line=="empty":
if queue:
print(0)
else:
print(1)
예전에 C할 때 구현했던 대로 front와 rear를 사용해서 푼 풀이도 있었다.
하지만 deque가 넘나 편리한 것..
반응형
'알고리즘 > Baekjoon' 카테고리의 다른 글
[CodingTest] 백준 #11866 요세푸스 문제 0 (0) | 2021.12.08 |
---|---|
[CodingTest] 백준 #2164 카드 2 (0) | 2021.12.08 |
[CodingTest] 백준 #3009 네 번째 점 (0) | 2021.12.07 |
[CodingTest] 백준 #2439 별 찍기 - 2 (2) | 2021.12.07 |
[CodingTest] 백준 #2438 별 찍기 - 1 (0) | 2021.12.07 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- brute force
- html
- web
- 파이썬
- javascript
- 덱
- Oracle
- 문자열
- 스프링
- CSS
- 고득점 키트
- 큐
- Java
- append
- 백준
- python
- bootstrap
- jsp
- Django
- jQuery
- 정렬
- 프로그래머스
- 장고
- 자바스크립트
- 브루트 포스
- R
- Case When
- baekjoon
- 단계별로풀어보기
- 자바
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함