๐Ÿ“’ 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
}