seunghyun Note
[백준] 18258번 : 큐 2 with JS 본문
링크 : https://www.acmicpc.net/problem/18258
18258번: 큐 2
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
문제 풀이
링크드리스트를 공부하고 큐 문제를 해결하려고 했다.
결국 문제를 해결했지만 정말 문제가 더티하다....
이 문제는 아래의 순서로 공부를 하면 풀 수 있었다.
1. linked list를 아는가?
2024.01.23 - [코딩테스트/코테를 위한 알고리즘 & 자료구조 정리] - Singly Linked Lists with JS
Singly Linked Lists with JS
코딩테스트를 공부하면서 프로그래머스 lv0~lv1 쉬운 버전들, 백준 실버 5 까지는 풀어도 linked list, stack & queue, tree 등 다양한 자료구조와 알고리즘 문제들이 나오면 과거에 배웠던 것을 망각하고
cojjangsh.tistory.com
2. stack & queue 개념을 아는가?
[자료구조] 스택 (STACK), 큐(QUEUE) 개념/비교 /활용 예시
[자료구조] 스택 (STACK), 큐(QUEUE) 개념/비교 /활용 예시/ 실생활 활용 스택 (STACK)이란? 📌 스택의 개념 스택(stack)이란 쌓아 올린다는 것을 의미한다. 따라서 스택 자료구조라는 것은 책을 쌓는 것
devuna.tistory.com
3. 속도 차이 : 큐 구현 vs 배열 객체 사용
JS 알고리즘 구현: 큐(Queue) 구현 vs Array 메서드(shift, splice) 사용했을때 속도 비교
알고리즘 코딩테스트에서 Queue 자료구조를 써야할때가 있습니다. 대표적으로 BFS를 구현할때죠.C++의 경우 STL을 통해 사용할 수 있고, Python의 경우 deque를 써서 삽입, 삭제 시 O(1)의 시간복잡도를
velog.io
이렇게만 하면 풀 수 있을줄 알았지만
마지막에 배열에 push 가 아닌
문자열에 저장 후에 join을 해서 데이터 크기를 줄이는 작업까지 해야 성공이다.
const fs = require("fs");
const [n, ...arr] = fs.readFileSync("/dev/stdin").toString().trim().split("\n");
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.tail = null;
this.head = null;
this.length = 0;
}
enqueue(value) {
let newNode = new Node(value);
this.length++;
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
pop() {
if (!this.head) return -1;
let pop = this.head;
this.head = pop.next;
this.length--;
return pop.value;
}
front() {
if (!this.head) return -1;
return this.head.value;
}
back() {
if (!this.head) return -1;
return this.tail.value;
}
empty() {
if (!this.head) return 1;
else return 0;
}
size() {
return this.length;
}
}
let queue = new Queue();
let answer = "";
for (let i = 0; i < n; i++) {
let [cmd, value] = arr[i].split(" ");
switch (cmd) {
case "push":
queue.enqueue(Number(value));
break;
case "pop":
answer += queue.pop() + " ";
break;
case "size":
answer += queue.size() + " ";
break;
case "empty":
answer += queue.empty() + " ";
break;
case "front":
answer += queue.front() + " ";
break;
case "back":
answer += queue.back() + " ";
break;
default:
break;
}
}
console.log(answer.split(" ").join("\n"));
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] n^2 배열 자르기 with JS (0) | 2024.01.29 |
---|---|
[백준] 2164 카드2 with JS (0) | 2024.01.24 |
[프로그래머스] 배열의 원소 삭제하기 with JS (0) | 2024.01.23 |
[백준] 12789번 : 도키도키 간식드리미(스택 공부 부수기) with JS (0) | 2024.01.20 |
[백준] 4949번 : 균형잡힌 세상(스택 공부 부수기) with JS (0) | 2024.01.18 |