๐ Algorithm
[์ฝ๋ฉ ํ ์คํธ ํฉ๊ฒฉ์ ๋๊ธฐ] ๋ฌธ์ 15 ์์ธํธ์ค ๋ฌธ์
s2ylvia
2024. 9. 4. 12:54
๋ฌธ์ ์ค๋ช
N๋ช ์ ์ฌ๋์ด ์ ํํ๋ก ์ ์์ต๋๋ค. ๊ฐ ์ฌ๋์ 1๋ถํฐ N๊น์ง ๋ฒํธํ๋ฅผ ๊ฐ๊ณ ์์ต๋๋ค. ๊ทธ๋ฆฌ๊ณ ์์์ ์ซ์ K๊ฐ ์ฃผ์ด์ก์ ๋ ๋ค์๊ณผ ๊ฐ์ด ์ฌ๋์ ์์ฑ๋๋ค.
- 1๋ฒ ๋ฒํธํ๋ฅผ ๊ฐ์ง ์ฌ๋์ ๊ธฐ์ค์ผ๋ก K๋ฒ์งธ ์ฌ๋์ ์์ฑ๋๋ค.
- ์์ค ์ฌ๋ ๋ค์ ์ฌ๋์ ๊ธฐ์ค์ผ๋ก ํ๊ณ ๋ค์ K๋ฒ์งธ ์ฌ๋์ ์์ฑ๋๋ค.
N๊ณผ K๊ฐ ์ฃผ์ด์ง ๋ ๋ง์ง๋ง์ ์ด์์๋ ์ฌ๋์ ๋ฒํธ๋ฅผ ๋ฐํํ๋ solution() ํจ์๋ฅผ ๊ตฌํํด์ฃผ์ธ์.
์ ์ฝ ์กฐ๊ฑด
- N๊ณผ K๋ 1์ด์ 1000์ดํ์ ์์ฐ์์ ๋๋ค.
์ ์ถ๋ ฅ์ ์
N | K | return |
5 | 2 | 3 |
์ ๋ต
Class Queue{
items = [];
front = 0; //์
rear = 0; //๋ค
push(item){
this.items.push(item);
this.rear++; //๋ค๋ก ๋ฃ์ผ๋๊น
}
pop(){
return this.items[this.front++]; //์์์ ๊บผ๋ด์จ๋ค
}
size(){
return this.rear - this.front;
}
isEmpty(){
return this.front === this.rear;
}
}
solution(n,k){
//์์๋ฅผ ๋ค ํ์ ์ง์ด๋ฃ๋๋ค.
const queue = new Queue();
for(let i=1; i<=n; i++){
queue.push(i);
}
while(queue.size() > 1){
//์์๊ฐ ํ๋๋ง ๋จ์๋๊น์ง loop
for(let i=1; i<=k-1; i++){
queue.push(queue.pop()); //k-1๋ฒ popํ ๋ค ๋ค์ push
}
queue.pop(); //๊ทธ๋ฆฌ๊ณ ์์ ์จ ์ ๋ฅผ ์ ๊ฑฐ
}
//๋ค ๋๊ณ ํ๋๋ง ๋จ์ผ๋ฉด
return queue.pop(); //๋ง์ง๋ง ์์ return
}