Algorithm/Programmers

[JavaScript] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋ฌด์ง€์˜ ๋จน๋ฐฉ ๋ผ์ด๋ธŒ

๊ฐœ๋ฐœ๊ฐœ๊ตด๐Ÿธ 2022. 9. 11. 22:45

[๋ฌธ์ œ]

https://school.programmers.co.kr/learn/courses/30/lessons/42891

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

[ํ’€์ด]

๋ฌธ์ œ์˜ ํ•ต์‹ฌ์€ ์ด๋ถ„ํƒ์ƒ‰์„ ํ†ตํ•ด ํšŒ์ „ํŒ์ด ๋ช‡๋ฒˆ์งธ ๋Œ์•˜์„ ๋•Œ k+1์ดˆ๊ฐ€ ๋˜๋Š”์ง€ ์ฐพ์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

์˜ˆ๋ฅผ ๋“ค์–ด ํšŒ์ „ํŒ์ด [3, 1, 2]์ด๊ณ  k๊ฐ€ 5๋ผ๋ฉด k+1์ธ 6์ดˆ์— ์–ด๋–ค ๊ทธ๋ฆ‡์„ ๋จน๋Š”์ง€ ์ฐพ์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค.

  • 1ํšŒ์ „ : [2, 0, 1] -> 3์ดˆ ์ง€๋‚จ
  • 2ํšŒ์ „ : [1, 0, 0] -> 5์ดˆ ์ง€๋‚จ
  • 3ํšŒ์ „ : [0, 0, 0] -> 6์ดˆ ์ง€๋‚จ

๋”ฐ๋ผ์„œ 3ํšŒ์ „์— 6์ดˆ๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ 3ํšŒ์ „์„ ๊ฒ€์ƒ‰ํ•˜์—ฌ 1๋ฒˆ ๊ทธ๋ฆ‡์„ ๋จน๋Š”๊ฒƒ์„ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

 

์ด๋ถ„ํƒ์ƒ‰์„ ์‚ฌ์šฉํ•˜์—ฌ k+1์ด ํฌํ•จ๋œ ํšŒ์ „์„ ์ฐพ๋Š” ๊ณผ์ •์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

์ดˆ๊ธฐ ์„ธํŒ…

  • ์ตœ์†Œ ํšŒ์ „์ˆ˜ left = 1;
  • ์ตœ๋Œ€ ํšŒ์ „์ˆ˜ right = 6; (๋ชจ๋“  ๊ทธ๋ฆ‡์˜ ์ดํ•ฉ = 3 + 1 + 2)

์ด๋ถ„ํƒ์ƒ‰ ๊ณผ์ •

  • mid = (left + right)/2 = 3 => 3ํšŒ์ „ ์†Œ์š” ์‹œ๊ฐ„์€ 6์ด๋ฏ€๋กœ right = 2 ๋กœ ๊ฐฑ์‹  
  • mid = 1 ์ด๋ฏ€๋กœ 1ํšŒ์ „ ์†Œ์š” ์‹œ๊ฐ„์€ 3์ด๋ฏ€๋กœ left = 2๋กœ ๊ฐฑ์‹ 
  • mid = 2 ์ด๋ฏ€๋กœ 2ํšŒ์ „ ์†Œ์š”์‹œ๊ฐ„์€ 5์ด๋ฏ€๋กœ left = 3์œผ๋กœ ๊ฐฑ์‹ 
  • ์ด๋ถ„ํƒ์ƒ‰์ด ์ข…๋ฃŒ๋˜๊ณ  left = 3์ด๋ฏ€๋กœ 3ํšŒ์ „์‹œ ์šฐ๋ฆฌ๊ฐ€ ์ฐพ๋Š” k+1์ด ํฌํ•จ

๋”ฐ๋ผ์„œ left - 1 (2) ํšŒ์ „์ด ๋๋‚œํ›„ ์‹œ๊ฐ„์€ 5์ดˆ์ด๊ณ , 2ํšŒ์ „์ด ๋๋‚œํ›„ ํšŒ์ „ํŒ์˜ ์Œ์‹ ์ƒํƒœ food๋ฐฐ์—ด์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

[ [ 3, 1 ] ]

 

๋”ฐ๋ผ์„œ 6์ดˆ์ผ๋•Œ๋Š” 1๋ฒˆ ํšŒ์ „ํŒ์„ ๋จน๊ฒŒ๋ฉ๋‹ˆ๋‹ค.

 

[์ฝ”๋“œ]

function solution(food_times, k) {
    var answer = -1;
    let sum = food_times.reduce((acc, cur) => acc + cur);
    if(sum < k) {
        return answer;
    }
    
    // ์ตœ์†Œ rotate 1, ์ตœ๋Œ€ rotate 6
    let left = 1;
    let right = sum;
    while(left <= right) {
        let mid = Math.floor((left + right)/2);
        let time = 0;
        food_times.forEach((i) => {
            if(i <= mid) {
                time += i;
            } else {
                time += mid;
            }
        });
        if(time < k+1) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    let time = 0;
    left--;
    food_times.forEach((i) => {
        if(i <= left) {
            time += i;
        } else {
            time += left;
        }
    });
    let foods = food_times.map((i, idx) => [i, idx+1]).filter((i) => i[0] > left);
    for(let i=0;i<foods.length;i++) {
        time++;
        if(time === k+1) {
            answer = foods[i][1];
            break;
        }
    }
    return answer;
}