์ฒ์ ํ์ด (์๊ฐ ์ด๊ณผ)
const fs = require('fs');
let input = (fs.readFileSync('./test') + '').toString().trim();
const numArr = Array.from({ length: parseInt(input) }, (v, i) => i + 1);
while (numArr.length > 1) {
numArr.shift();
numArr.push(numArr.shift());
}
console.log(numArr[0]);
๋ฐฐ์ด์ ๋๋ฉฐ ๊ธธ์ด๊ฐ 1์ด๋ ๋๊น์ง
1. ์ฒซ ๋ฒ์งธ ๊ฐ ์ ๊ฑฐ
2. ์ฒซ ๋ฒ์งธ ๊ฐ ๋ค๋ก ๋ถ์ด๊ธฐ
๋ฐ๋ณตํ์ง๋ง... ์๊ฐ์ด๊ณผ
๊ฒ์ํด ๋ณด๋ ๋ฐฐ์ด์ push ,pop ์ ์ด์ฉํ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ฌ๋ค๊ณ ํ๋ค.
๋ฐฐ์ด์ ์ฐ์ฐ์๊ฐ์ ๋งจ ์ ์์์ ์ญ์ & ์ถ๊ฐํ๋ ์ฐ์ฐ์ด index ์์ ์๊ฐํ๋ ์๊ฐ์ด๋ ๋ค๋ฆ์๊ธฐ ๋๋ฌธ์
์ฐ๊ฒฐ๋ฆฌ์คํธ๋ฅผ ๋ง๋ค์ด์ ์ฌ์ฉํด์ผ ํ๋ค๋ ํ์ด@!!
ํ์ด์ฌ์ผ๋ก ํ ๋ ์ด๋ฐ๊ฑฐ ์์๋๋ฐ ..์์
JS๋ ์ฐ๊ฒฐ๋ฆฌ์คํธ๊ฐ ์์ด์ ์ง์ ๋ง๋ค์ด์ฃผ๋ฉด ๋๋จ๋ค~~ ์ ๋๋น!!
๐ค ๋งํฌ๋๋ฆฌ์คํธ?
๋งํฌ๋๋ฆฌ์คํธ๋ ๋ ธ๋๋ก ์ด๋ฃจ์ด์ ธ ์๊ณ val, ref,add ์ ์ฅํ๋ ๊ณต๊ฐ์ด ์์
- find ๋ฅผ ์ํด์๋ ์๊ฐ๋ณต์ก๋ O(n)
- random access๋ฅผ ์ํด์๋ head์์๋ถํฐ ๋ฌด์กฐ๊ฑด ์์ํด ๊ฐ๊ฐ์ node๋ฅผ ํ์ํด์ผ ํจ
- ํ ์ชฝ ๋ฐฉํฅ์ผ๋ก๋ง ์ฐ๊ฒฐ๋์ด์์ผ๋ฉด : singly linked list ์์ชฝ ๋ฐฉํฅ : doubly linked list (prev ๋ฐฉํฅ์ผ๋ก๋ ํ์์ด ๊ฐ๋ฅํจ)
๊ทธ๋ ๋ด ์ด ๋ฌธ์ ๋ฅผ ํ๊ธฐ ์ํด์๋
๋ฐฐ์ด์ฒ๋ผ ๊ฐ์ ๋นผ๊ณ ๋ฃ์๋๋ง๋ค ์ธ๋ฑ์ค๋ฅผ ์๋ก๊ณ์ฐํ์ง ์์๋ ๋๋ ๋งํฌ๋๋ฆฌ์คํธ๋ฅผ ์ง์ ๊ตฌํํด์ผ ํ๋ค!
โค๏ธ nodejs ๋งํฌ๋๋ฆฌ์คํธ
class Node {
constructor(value) {
this.value = value;
this.next = null;
this.prev = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this._size = 0;
}
add(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
}
this.tail = newNode;
this._size++;
return newNode;
}
getHead() {
return this.head.value;
}
removeHead() {
this.head = this.head.next;
this.head.prev = null;
this._size--;
}
getSize() {
return this._size;
}
}
1. Node ํด๋์ค ์์ฑ ( ๊ฐ , ๋ค์๊ฐ , ์ด์ ๊ฐ )
2. LinkedList ํด๋์ค ์์ฑ ( ํค๋ , ๊ผฌ๋ฆฌ, ํฌ๊ธฐ)
3. ๋ฉ์๋ ์์ฑ
- add : ๊ฐ ์ถ๊ฐ
- getHead : ํ์ฌ ํค๋ ์ป๊ธฐ
- removeHead : ํค๋ ์ ๊ฑฐ
- getSize : ํ์ฌ ์ฌ์ด์ฆ
new cards
LinkedList { head: null, tail: null, _size: 0 }
์ด๊ธฐํ cards
LinkedList {
head: <ref *1> Node {
value: 1,
next: Node { value: 2, next: [Node], prev: [Circular *1] },
prev: null
},
tail: <ref *2> Node {
value: 6,
next: null,
prev: Node { value: 5, next: [Circular *2], prev: [Node] }
},
_size: 6
}
1~6์ ์ซ์๊ฐ ์ฑ์์ ธ์๊ณ ์๋ก ์ฐ๊ฒฐ๋์ด ์์ (1-2-3-4-5-6)
๋ค์ ํ์ด
const fs = require('fs');
let input = (fs.readFileSync('./test') + '').toString().trim();
const cards = new LinkedList();
for (let i = 1; i <= input; i++) {
cards.add(i);
}
while (cards.getSize() !== 1) {
cards.removeHead();
cards.add(cards.getHead());
cards.removeHead();
}
console.log(cards.getHead());
'๐ ์๊ณ ๋ฆฌ์ฆ > ๋ฐฑ์ค JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] node.js/ 10828 ์คํ (0) | 2021.10.15 |
---|---|
[๋ฐฑ์ค] node.js/ 3986 ์ข์ ๋จ์ด (0) | 2021.10.14 |
[๋ฐฑ์ค] node.js / 1158 ์์ธํธ์ค ๋ฌธ์ (2) | 2021.10.12 |
[๋ฐฑ์ค] JS/ 11399 ATM (0) | 2021.10.06 |
[๋ฐฑ์ค] JS/ 1157 ๋จ์ด ๊ณต๋ถ (0) | 2021.10.05 |
๋๊ธ