๋ณธ๋ฌธ์œผ๋กœ ๊ฑด๋„ˆ๋›ฐ๊ธฐ

42583. ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ


๋ฌธ์ œ ์œ ํ˜•๋‚œ์ด๋„๊ฑธ๋ฆฐ ์‹œ๊ฐ„ํ•ด๊ฒฐ ์œ ๋ฌด(โœ…/โŒ)
์Šคํƒ, ํlv.22์‹œ๊ฐ„โœ…

์„ค๊ณ„ ๋ฐฉ๋ฒ•#

  • ๋‹ค๋ฆฌ์˜ ๊ธธ์ด๋ฅผ ๊ณ ์ • ๊ธธ์ด๋กœ ๊ฐ€์ง€๋Š” ํ(ย onBridgeย )๋ฅผ ๋งŒ๋“ฌ.

    • Array๋ฅผ ํ๋กœ ์‚ฌ์šฉํ•˜๊ณ  index๋ฅผ ์ด๋™์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ (shiftย ์—ฐ์‚ฐ์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฌธ์ œ ํ•ด๊ฒฐ)

    • timeย ์„ ํ์˜ head index๋กœ ์‚ฌ์šฉ

  • overBridgeย ์— ๋ชจ๋“  ํŠธ๋Ÿญ์ด ๋„์ฐฉํ•  ๋•Œ ๊นŒ์ง€ ์‹œ๊ฐ„์„ ์ฆ๊ฐ€์‹œํ‚ค๊ณ ย onBridgeย ํ์—ํŠธ๋Ÿญ์„ ๋‹ด์•„๊ฐ€๋ฉฐ ์ง„ํ–‰

  • onBridgeWeightย ๋ฅผ ๋ฐ˜๋ณต๋ฌธ ๋‚ด์—์„œ ๊ณ„์‚ฐ

์ฝ”๋“œ#

function solution(birdge_length, weight, truck_weights) {    const onBridge = Array.from({length: birdge_length}, () => null);    const overBridge = [];    let onBridgeWeight = 0;    let time = 0;
    let waitingTruckIndex = 0;    while (overBridge.length !== truck_weights.length) {        const truck = onBridge[time];        time++;
        if (truck) {            overBridge.push(truck);            onBridgeWeight -= truck;        }
        if (            onBridgeWeight + truck_weights[waitingTruckIndex] > weight ||            waitingTruckIndex >= truck_weights.length        ) {            onBridge[time + birdge_length - 1] = null;            continue;        }
        onBridge[time + birdge_length - 1] = truck_weights[waitingTruckIndex];        onBridgeWeight += truck_weights[waitingTruckIndex];        waitingTruckIndex++;    }
    return time;}

์‹œ๊ฐ„ ๋ณต์žก๋„#

  • O(n), time ๋งŒํผ ๋ฐ˜๋ณต๋ฌธ ์—ฐ์‚ฐ

์–ด๋ ค์› ๋˜ ์ #

  • ์ฒ˜์Œ์— ๋ฌธ์ œ๋ฅผ ์ž˜๋ชป ์ดํ•ดํ•ด์„œ ์ฃผ์–ด์ง„ truck_weights ๋ฐฐ์—ด์„ ๋ณด๊ณ  ์ตœ์†Œ ์‹œ๊ฐ„์„ ์ฐพ์•„๋‚ด์•ผ๋˜๋Š” ๊ฑธ๋กœ ์ฐฉ๊ฐํ•จ.

  • JS์—์„œ ํ๋ฅผ ์“ฐ๋Š”๊ฒŒ ๋„ˆ๋ฌด ๋ถˆํŽธํ•จ