정현수
현수 세상
정현수
전체 방문자
오늘
어제
반응형
  • 분류 전체보기 (267)
    • NEXTSTEP 자바스크립트 클린코드 2기 (1)
    • 우테코 4기 (6)
    • 회고록 (5)
    • 개발지식 (6)
    • React (3)
      • React Clone Coding (3)
    • React Native (2)
    • Kubernetes & Docker (36)
      • 궁금한 것 (13)
    • Flutter (2)
    • 알고리즘 (168)
      • 프로그래머스 1단계 (27)
      • 프로그래머스 2단계 (37)
      • 백준 (98)
      • 이론 (6)
    • 자료구조 (3)
    • 유튜브 (1)
    • 책 읽자 (1)
    • 취업준비 (1)
    • 대내 활동 (31)
      • 2022년 겨울방학 알고리즘 특강 (0)
      • 2020년 여름방학 모각코 (13)
      • 2020년 겨울방학 모각코 (13)
      • 웹프로그래밍 상상튜터링 (5)

인기 글

최근 글

공지사항

  • 블로그 이동

태그

  • React
  • programmers
  • docker
  • kubelet
  • image pull
  • 프로그래머스
  • NodePort
  • 개발지식
  • replicaset
  • 리액트
  • 레플리카셋
  • Kubernetes
  • 공식문서
  • 디플로이먼트
  • 이코테
  • flutter
  • 노드
  • mysql
  • 파이썬
  • 모각코
  • javascript
  • 우테코
  • 그리디
  • 자바스크립트
  • image run
  • 알고리즘
  • 쿠버네티스
  • 백준
  • Jenkins
  • Deployment

최근 댓글

블로그 메뉴

  • 홈

티스토리

hELLO · Designed By 정상우.
정현수

현수 세상

[백준] 18258번: 큐 2 (JavaScript, NodeJS)
알고리즘/백준

[백준] 18258번: 큐 2 (JavaScript, NodeJS)

2022. 1. 9. 16:35
반응형

문제

정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 여섯 가지이다.

  • push X: 정수 X를 큐에 넣는 연산이다.
  • pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 큐에 들어있는 정수의 개수를 출력한다.
  • empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
  • front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.

입력

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.

출력

출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.

예제 입력 1 복사

15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front

예제 출력 1 복사

1
2
2
0
1
2
-1
0
1
-1
0
3

정답 풀이

const fs = require("fs");

// 백준 제출 할 때 주석 제거
// const readFileSyncAddress = '/dev/stdin';

// VSC 테스트 할 때 주석 제거
const readFileSyncAddress = "input.txt";

const input = fs.readFileSync(readFileSyncAddress).toString().trim().split("\n");

const [n, ...commands] = input;

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) {
			this.head = node;
			this.head.next = this.tail;
		} else {
			this.tail.next = node;
		}

		this.tail = node;
		this.size += 1;
	}

	getSize() {
		return this.size;
	}

	pop() {
		if (this.size > 2) {
			const item = this.head.item;
			const newHead = this.head.next;
			this.head = newHead;
			this.size -= 1;
			return item;
		} else if (this.size === 2) {
			const item = this.head.item;
			const newHead = this.head.next;
			this.head = newHead;
			this.tail = newHead;
			this.size -= 1;
			return item;
		} else if (this.size === 1) {
			const item = this.head.item;
			this.head = null;
			this.tail = null;
			this.size -= 1;
			return item;
		} else {
			return -1;
		}
	}

	empty() {
		return this.size ? 0 : 1;
	}

	front() {
		return this.head ? this.head.item : -1;
	}

	back() {
		return this.tail ? this.tail.item : -1;
	}
}

// 문제 풀이
function solution(n, commands) {
	let answer = '';
	const queue = new Queue();

	for (let i = 0; i < n; i += 1) {
		const command = commands[i].split(' ')[0];

		switch (command) {
			case 'push':
				const pushItem = commands[i].split(' ')[1];
				queue.push(pushItem);
				break;
			case 'pop':
				answer += queue.pop() + ' ';
				break;
			case 'front':
				answer += queue.front() + ' ';
				break;
			case 'back':
				answer += queue.back() + ' ';
				break;
			case 'empty':
				answer += queue.empty() + ' ';
				break;
			case 'size':
				answer += queue.getSize() + ' ';
				break;
			default:
				break;
		}
	}

	return answer.split(' ').join('\n');
}

// 제출
const answer = solution(n, commands);
console.log(answer);

 

자바스크립트 내장 함수 (split, splice, pop, shift)와 같은 함수와

직접 노드를 이용해서 큐를 구현하는 것의 시간 차이를 비교한 포스트가 있다.

 

https://velog.io/@grap3fruit/JS-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%EA%B5%AC%ED%98%84-%ED%81%90Queue-%EA%B5%AC%ED%98%84%ED%96%88%EC%9D%84%EB%95%8C-vs-Array-%EB%A9%94%EC%84%9C%EB%93%9Cshift-splice-%EC%82%AC%EC%9A%A9%ED%96%88%EC%9D%84%EB%95%8C-%EC%86%8D%EB%8F%84-%EB%B9%84%EA%B5%90

 

JS 알고리즘 구현: 큐(Queue) 구현 vs Array 메서드(shift, splice) 사용했을때 속도 비교

알고리즘 코딩테스트에서 Queue 자료구조를 써야할때가 있습니다. 대표적으로 BFS를 구현할때죠.C++의 경우 STL을 통해 사용할 수 있고, Python의 경우 deque를 써서 삽입, 삭제 시 O(1)의 시간복잡도를

velog.io

 

직접 구현하는 것이 최대 1000배까지 빠르다고하니, 당연히 시간초과가 나는 것이 당연했다.

직접 자료구조를 만드는 연습을 해야할 것 같다.

반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 1874번: 스택 수열 (JavaScript, NodeJS)  (0) 2022.01.10
[백준] 10866번: 덱 (JavaScript, NodeJS)  (0) 2022.01.10
[백준] 10828번: 스택 (JavaScript, NodeJS)  (0) 2022.01.09
[백준] 1158번: 요세푸스 문제 (JavaScript, NodeJS)  (0) 2022.01.09
[백준] 1715번: 카드 정렬하기 (JavaScript, NodeJS)  (0) 2022.01.08
    정현수
    정현수
    깃허브 : https://github.com/junghyeonsu 개인 블로그 : https://junghyeonsu.com/ (양질의 글을 올리려고 항상 노력합니다.)

    티스토리툴바