
const fs = require('fs');
const path = process.platform === 'linux' ? '/dev/stdin' : 'Wiki\\input.txt';
const [n, ...inputs] = fs.readFileSync(path).toString().trim().split('\r\n');
const q = [];
const ans = [];
for (const input of inputs) {
const [comment, num] = input.split(' ');
const len = q.length;
if (comment === 'size') ans.push(len.toString());
else if (comment === 'empty') ans.push(len ? '0' : '1');
else if (comment === 'front') ans.push(len ? q[0].toString() : '-1');
else if (comment === 'back') ans.push(len ? q[len - 1].toString() : '-1');
else if (comment === 'pop') {
if (len === 0) {
ans.push('-1');
continue;
}
ans.push(q.shift(num).toString());
} else if (comment === 'push') {
q.push(num);
continue;
}
}
console.log(ans.join('\n'));
⏰ 소요한 시간 : 10분
아주 더러운.. 문제유형
각 코멘트에 따라 문제에서 설명 하는 연산을 하면된다.
이 때 중요한 점은 시간제한이 0.5초이기 때문에 pop연산만 있을 경우를 고려해주어야 된다.
문제에서 정의한 pop연산은 shift() 연산으로 O(n)의 시간이 소요되는데 문제에서 n이 10,000이므로 최악의 경우 1초정도의 시간 복잡도가 걸린다. 하지만 pop 연산의 경우 큐가 비어있다면 수행하지 못하기 때문에 조건 분기를 따로 해준다.
그리고 매번 console.log()를 수행하는 것 또한 시간소요가 되기 때문에 정답을 ans 배열에 문자열 형태로 삽입한 후 join 연산으로 더해준다.