์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜6] ๊ณต์ฃผ ๊ตฌํ•˜๊ธฐ (Javascript)

์€์ง„ 2021. 6. 27. 03:20

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜6] ๊ณต์ฃผ ๊ตฌํ•˜๊ธฐ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-27 queue๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฌธ์ œ์ž„์„ ๋Šฆ๊ฒŒ ํŒŒ์•…


์ฒซ๋ฒˆ์งธ ์‹œ๋„ : stack ์‚ฌ์šฉ

1. ์™•์ž๊ฐ€ ํŠน์ •์ˆซ์ž K๋ฅผ ์™ธ์น˜๋ฉด ์ œ์™ธ, ์ฒ˜์Œ๋ถ€ํ„ฐ ์‹œ์ž‘

2. stack ์„ ์ƒ์„ฑํ•˜์—ฌ ์ดˆ๊ธฐ๊ฐ’ 1, ์ œ์™ธ๋˜๋ฉด 0

let stack = Array.from({length: n}, v => 0);

3. ์™•์ž ์ œ์™ธ ๋กœ์ง

  • stack ๊ฐ’์ด 1์ธ ๊ฒฝ์šฐ, num++
  • num === k ์ธ ๊ฒฝ์šฐ stack ๊ฐ’์€ 0, num === 0;

์„ฑ๋Šฅ ์ด์Šˆ ์˜ˆ์ธก
์ˆ˜๋งŽ์€ ์™•์ž๊ฐ€ ์ œ์™ธ๋œ ์ƒํ™ฉ์—์„œ๋„ stack์„ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€ ์ˆœํšŒ

๋ฌธ์ œ์ 
๋งˆ์ง€๋ง‰ ๋‚จ์€ ์™•์ž๋ฅผ ์ถœ๋ ฅํ•ด์•ผ ํ•จ
๋งค๋ฒˆ 1์ธ stack๊ฐ’์ด ๋ช‡ ๊ฐœ์ธ์ง€ ํ™•์ธํ•ด์•ผ ํ•จ

4. stack์— 1๋ฒˆ๋ถ€ํ„ฐ n๋ฒˆ๊นŒ์ง€ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ •

let stack = Array.from({length: n-1}, (v, i) => i+1);

5. k๋ฅผ ์™ธ์นœ ์™•์ž๋Š” stack.pop();

  • while (stack.length > 1)
  • stack ์ˆœํšŒํ•˜๋‹ค๊ฐ€ ์ค‘๊ฐ„์— ๊ฐ’์„ ์‚ญ์ œํ•˜๋ฏ€๋กœ stack์ด๋ผ ํ•  ์ˆ˜ ์—†๊ตฐ. stack์ด ์•„๋‹ˆ๋„ค



1. stack์— 1๋ฒˆ๋ถ€ํ„ฐ n๋ฒˆ๊นŒ์ง€ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ • [1, 2, 3, โ€ฆ , n]

let stack = Array.from({length: n-1}, (v, i) => i+1);

2. for๋ฌธ์œผ๋กœ stack์„ ์ˆœํšŒ

  • ์ˆœํšŒํ•  ๋•Œ๋งˆ๋‹ค newStack.push(); num++
  • num === k์ธ ๊ฒฝ์šฐ num = 0;
  • stack ํ•œ๋ฐ”ํ€ด ์ˆœํšŒํ•œ ๊ฒฝ์šฐ, stack = newStack ์„ค์ •

๋ฌธ์ œ์ 
javascript ํŠน์„ฑ์ƒ ๋ฐฐ์—ด ๋ณต์‚ฌ arr.slice()๋ฅผ ์จ์•ผํ•˜๋Š”๋ฐ, ์•ˆ์“ธ ์ˆ˜ ์—†๋‚˜?



๋‘๋ฒˆ์งธ ์‹œ๋„ : queue ์‚ฌ์šฉ

1. queue 1๋ฒˆ๋ถ€ํ„ฐ n๋ฒˆ๊นŒ์ง€ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ • [1, 2, 3, โ€ฆ , n]

let queue = Array.from({length: n-1}, (v, i) => i+1);

2. queue ์ˆœํšŒ

  • ์ˆœํšŒํ•  ๋•Œ๋งˆ๋‹ค cnt++, queue.push(queue.shift());
  • cnt === k ์ธ ๊ฒฝ์šฐ cnt = 0, queue.shift();
while (queue.length > 1) {
    let num = queue.shift();

    if (cnt === k) cnt = 0;
    else {
        queue.push(num);
        cnt++;
    }
}

return queue.shift();


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-27

function solution(n, k) {
    let queue = Array.from({length: n}, (v, i) => i+1);
    let cnt = 0;

    while (queue.length > 1) {
        let num = queue.shift();
        cnt++;

        if (cnt === k) cnt = 0;
        else queue.push(num);
    }

    return queue.shift();
}