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

42862. ์ฒด์œก๋ณต

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ฒด์œก๋ณต


๋ฌธ์ œ ์œ ํ˜•๋‚œ์ด๋„๊ฑธ๋ฆฐ ์‹œ๊ฐ„ํ•ด๊ฒฐ ์œ ๋ฌด(โœ…/โŒ)
ํƒ์š•๋ฒ•(๊ทธ๋ฆฌ๋””)lv.11์‹œ๊ฐ„โœ…

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

  • Set์„ ์‚ฌ์šฉํ•ด์„œ reserve ์™€ lost ์˜ ์ฐจ์ง‘ํ•ฉ์œผ๋กœ reserveSet , lostSet ์„๋งŒ๋“ ๋‹ค.

  • reserveSet ์„ ์ˆœํšŒํ•˜๋ฉด์„œ ์•ž์˜ ํ•™์ƒ์ด ์ฒด์œก๋ณต์ด ์—†๋‹ค๋ฉด ์ฒด์œก๋ณต์„ ๋นŒ๋ ค์ฃผ๊ณ 

  • ๋’ค์˜ ํ•™์ƒ์ด ์ฒด์œก๋ณต์ด ์—†๋‹ค๋ฉด ์ฒด์œก๋ณต์„ ๋นŒ๋ ค์ค€๋‹ค.

  • ์ด ํ•™์ƒ์—์„œ lostSet.size ๋งŒํผ์„ ์ œ๊ฑฐํ•œ๋‹ค.

์ฝ”๋“œ#

Set.prototype.difference = function (setB) {    let difference = new Set(this);    for (let elem of setB) {        difference.delete(elem);    }    return difference;};
function solution(n, lost, reserve) {    const reserveSet = new Set(reserve).difference(new Set(lost));    const lostSet = new Set(lost).difference(new Set(reserve));
    reserveSet.forEach((i) => {        if (lostSet.has(i - 1)) {            lostSet.delete(i - 1);        } else if (lostSet.has(i + 1)) {            lostSet.delete(i + 1);        }    });
    return n - lostSet.size;}

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

โ˜ Set์˜ has , delete , add ์—ฐ์‚ฐ์ด O(1) ์ด๋ผ๋Š” ์ ์„ ์ƒˆ๋กญ๊ฒŒ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค. (๋ฐฐ์—ด์€ O(n))

  • N = reserveSet , M = lostSet

  • ์ฐจ์ง‘ํ•ฉ ์ƒ์„ฑ : O(N), O(M)

  • reserveSet ์ˆœํšŒ ๋ฐ lostSet ๊ฒ€์ƒ‰ : O(NM)

  • ์ด O(NM)

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

  • ๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ๋Œ€ํ•œ ์ดํ•ด๊ฐ€ ๋ถ€์กฑํ–ˆ๋‹ค.

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

How to make your code faster using JavaScript Sets