문제
정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여섯 가지이다.
- push X: 정수 X를 큐에 넣는 연산이다.
- pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- size: 큐에 들어있는 정수의 개수를 출력한다.
- empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
- front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
입력
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
입출력 예시
입력
15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front
출력
1
2
2
0
1
2
-1
0
1
-1
0
3
풀이
'use strict';
const fs = require('fs');
// 백준 제출 할 때 주석 제거
// const readFileSyncAddress = '/dev/stdin';
// VSC 테스트 할 때 주석 제거
const readFileSyncAddress = 'input.txt';
const input = fs.readFileSync(readFileSyncAddress).toString().trim().split('\n');
const N = input.shift();
class Node {
constructor(item) {
this.item = item;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
push(item) {
const node = new Node(item);
if (this.head === null) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.size += 1;
}
length() {
return this.size;
}
popLeft() {
if (this.empty()) {
return -1;
}
const node = this.head;
this.head = this.head.next;
this.size -= 1;
return node.item;
}
front() {
if (this.empty()) return -1;
return this.head.item;
}
back() {
if (this.empty()) return -1;
return this.tail.item;
}
empty() {
if (this.head === null) {
return 1;
}
return 0;
}
}
function solution() {
let answer = [];
const queue = new Queue();
for (let command of input) {
const c = command.split(' ');
switch (c[0]) {
case 'push':
queue.push(c[1]);
break;
case 'pop':
answer.push(queue.popLeft());
break;
case 'size':
answer.push(queue.length());
break;
case 'empty':
answer.push(queue.empty());
break;
case 'front':
answer.push(queue.front());
break;
case 'back':
answer.push(queue.back());
break;
}
}
return answer;
}
const answer = solution();
console.log(answer.join('\n'));
처음에는 자바스크립트 내장 함수 ( push, pop, shift, unshift 등 ) 를 사용하여 구현하였는데 시간 초과가 떠 문제를 해결할 수 없었다.
그래서 찾아보니 내장 함수를 사용하는 방식과 직접 노드를 이용해 큐를 구현하는 방식 간에는 최대 1000배의 성능 차이가 난다고 한다.
그러니 시간초과가 날 수 밖에 없던 것이었다!
아래는 두 방식을 직접 비교해 본 포스트이다. 아래 링크를 통해 자세한 내용을 확인해볼 수 있다!
JS 알고리즘 구현: 큐(Queue) 구현 vs Array 메서드(shift, splice) 사용했을때 속도 비교
알고리즘 코딩테스트에서 Queue 자료구조를 써야할때가 있습니다. 대표적으로 BFS를 구현할때죠.C++의 경우 STL을 통해 사용할 수 있고, Python의 경우 deque를 써서 삽입, 삭제 시 O(1)의 시간복잡도를
velog.io
'알고리즘' 카테고리의 다른 글
[ 백준 ] 1158 요세푸스 문제 - JavaScript (0) | 2025.01.02 |
---|---|
[ 백준 ] 10828 스택 - JavaScript (0) | 2025.01.01 |
[ 구름 ] 구름 RPG 2 - Python (2) | 2024.09.23 |
[ 구름 ] 시간복잡도 - JavaScript (0) | 2024.09.23 |
[ 구름 ] 타임 세일 - JavaScript (0) | 2024.09.20 |