📄 문제
😅 나의 실패 풀이
const fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString().trim().split("\n");
let targetNum = parseInt(input[0]);
function go(num) {
let arr=[]
for (let i = 1; i <= num; i++){
arr.push(i)
}
while (arr.length != 1) {
arr.shift()
arr.push(arr.shift())
}
}
go(targetNum)
😂 실패 풀이 접근법
1. arr(빈 배열)을 만들고 반복문으로 targetNum 까지 순서대로 넣어준다.
2. 반복 arr의 길이가 1일 때 까지=> 맨 앞에 요소를 없애고, 맨 뒤에 맨 앞에 요소를 없애면서 넣어준다.
3. 시간 초과... 최대한 적은 수행으로 짠 것 같은데, 이 방법 자체가 안된다는 걸 깨달았다.
🤔 왜 그럴까?
- 채점 중이 뜨는 걸 보면 값은 잘 나온 것 같다.
- 배열의 shift, push 로는 시간 복잡도가 커질 수 밖에 없다고 한다.
- 우리 팀 그린이 말했던 말이 떠올라 연결리스트 구조로 접근을 해야한다고 생각이 들어 책으로 공부해서 수정 시작!
- 구현 성공!
📝 나의 통과 풀이
const fs = require("fs");
let input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");
let targetNum = parseInt(input.shift());
function linkedListNode(data) {
this.data = data;
this.next = null;
this.prev = null;
}
function linkedList() {
this.head = null;
this.tail = null;
this.size = 0;
}
linkedList.prototype.insert = function (value) {
let node = new linkedListNode(value);
if (!this.head) {
this.head = node;
} else {
this.tail.next = node;
node.tail = this.tail;
}
this.tail = node;
this.size++;
};
linkedList.prototype.remove = function () {
this.head = this.head.next;
this.head.tail = null;
this.size--;
};
linkedList.prototype.checkHead = function(){
return this.head.data;
}
linkedList.prototype.checkSize = function(){
return this.size
}
let item = new linkedList();
for (let i = 1; i <= targetNum; i++) {
item.insert(i);
}
while (item.checkSize() !== 1) {
item.remove();
item.insert(item.checkHead());
item.remove();
}
console.log(item.checkHead());
⌨ 접근법
1. 연결리스트 구조를 prototype으로 직접 구현한다 (생성, 추가, 삭제, 헤드체크, 사이즈체크 추가)
2. 반복문으로 실패 풀이와 동일한 구조 실행
* 추후에 알고리즘 개념 등도 포스팅 할 예정! *
📚 문제 링크
https://www.acmicpc.net/problem/2164
2164번: 카드2
N장의 카드가 있다. 각각의 카드는 차례로 1부터 N까지의 번호가 붙어 있으며, 1번 카드가 제일 위에, N번 카드가 제일 아래인 상태로 순서대로 카드가 놓여 있다. 이제 다음과 같은 동작을 카드가
www.acmicpc.net
'TEAM 알고싶다 > 성공 문제' 카테고리의 다른 글
[Baekjoon (Node.js)] 24479번 알고리즘 수업 - 깊이 우선 탐색 1 (0) | 2022.07.13 |
---|---|
[Baekjoon (Node.js)] 2606번 바이러스 (0) | 2022.07.05 |
[프로그래머스] JavaScript - 캐시 (0) | 2022.06.17 |
[LeetCode] 152. Maximum Product Subarray(최대로 생성된 부분 배열?) (0) | 2022.06.14 |
[LeetCode] 41. First Missing Positive (처음 누락된 양수?) (0) | 2022.06.13 |