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

42842. ์นดํŽซ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์นดํŽซ


๋ฌธ์ œ ์œ ํ˜•๋‚œ์ด๋„๊ฑธ๋ฆฐ ์‹œ๊ฐ„ํ•ด๊ฒฐ ์œ ๋ฌด(โœ…/โŒ)
์™„์ „ํƒ์ƒ‰lv.220๋ถ„โœ…

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

  • brownย ,ย yellowย ,ย return([x, y])ย ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ด€๊ณ„๋ฅผ ๊ฐ€์ง„๋‹ค.

    x * y === brown + yellow(x * 2) + (y * 2) - 4 === brown;(x - 2) * (y - 2) === yellow;
  • ๋จผ์ € ์ฒซ ๋ฒˆ์งธ ์„ฑ์งˆ์„ ์ด์šฉํ•ด์„œ, ์ธ์ˆ˜ ์Œ(FactorPairs)์„ ์ฐพ๋Š”๋‹ค.

  • ๊ฐ ์ธ์ˆ˜ ์Œ์„ reduce๋กœ ์ˆœํšŒํ•˜๋ฉฐ, ๋‘ ๋ฒˆ์งธ, ์„ธ ๋ฒˆ์งธ ์„ฑ์งˆ์„ ๋ชจ๋‘ ๋งŒ์กฑํ•˜๋Š” ์ธ์ˆ˜ ์Œ์„ ์ฐพ์œผ๋ฉด,ย splice(0)๋กœ early break ํ•˜๊ณ  ์ธ์ˆ˜ ์Œ์„ ๋ฆฌํ„ดํ•œ๋‹ค.

์ฝ”๋“œ#

function solution(brown, yellow) {    // (x * 2) + (y * 2) - 4 = brown;    // (x - 2) * (y - 2) = yellow;    // x * y = brown + yellow
    return findFactorPairs(brown + yellow).reduce((_, [x, y], __, pairs) => {        if (x * 2 + y * 2 - 4 === brown && (x - 2) * (y - 2) === yellow) {            pairs.splice(0);            return [x, y];        }    }, []);}
function findFactorPairs(number) {    const pairs = [[number, 1]];
    for (let i = 2; i <= Math.sqrt(number); i++) {        if (number % i === 0) {            pairs.push([number / i, i]);        }    }
    return pairs;}

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

  • findFactorPairย : O(root(N)) .. ?

  • FactorPairsย ์ˆœํšŒ : O(N) (์ˆœ์„œ์Œ์˜ ๊ฐœ์ˆ˜๋Š” ์ตœ๋Œ€ N/2 ์ด๋ฏ€๋กœ .. ?)> O(N * root(N));

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

  • ๊ทœ์น™์„ ์ฐพ์•„๋‚ด๋Š”๋ฐ์— ์ˆ˜ํ•™์ ์ธ ์‚ฌ๊ณ ๊ฐ€ ํ•„์š”ํ–ˆ๋‹ค.

์ฐธ๊ณ ์ž๋ฃŒ#

SplashLearn - Fun Math Practice Games for Kindergarten to 5th Grade