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

42579. ๋ฒ ์ŠคํŠธ ์•จ๋ฒ”

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ฒ ์ŠคํŠธ์•จ๋ฒ”


๋ฌธ์ œ ์œ ํ˜•๋‚œ์ด๋„๊ฑธ๋ฆฐ ์‹œ๊ฐ„ํ•ด๊ฒฐ ์œ ๋ฌด(โœ…/โŒ)
ํ•ด์‹œlv.31์‹œ๊ฐ„โœ…

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

  • genresย ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ,ย genres์™€ย plays์˜ย index๊ฐ€ ๊ฐ™์œผ๋ฏ€๋กœ, ์žฅ๋ฅด๋ณ„๋กœ ย first,ย second,ย sum์„ ๊ธฐ๋กํ•œย hashMapย ์„ ๊ตฌ์„ฑํ•œ๋‹ค.

  • hashMap์˜ย values๋ฅผย sum์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•œ ์ดํ›„, ์ˆœํšŒํ•˜๋ฉฐ ์žฅ๋ฅด๋ณ„ ย first,ย second๋กœ ์•จ๋ฒ”์„ ๊ตฌ์„ฑํ•œ๋‹ค.

์ฝ”๋“œ#

function solution(genres, plays) {    const hashMap = genres.reduce((hash, genre, i) => {        if (hash.has(genre)) {            const info = hash.get(genre);            if (plays[info.first] < plays[i]) {                info.second = info.first;                info.first = i;            } else if (info.second === null || plays[info.second] < plays[i]) {                info.second = i;            }            info.sum += plays[i];        } else {            hash.set(genre, {                first: i,                second: null,                sum: plays[i],            });        }        return hash;    }, new Map());
    return [...hashMap.values()]        .sort((a, b) => b.sum - a.sum)        .reduce(            (album, genre) =>                genre.second === null                    ? [...album, genre.first]                    : [...album, genre.first, genre.second],            [],        );}

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

  • hashMap ๊ตฌ์„ฑ : O(N)

  • hashMap ์ •๋ ฌ : O(NlogN)

  • hashMap ์ˆœํšŒ: O(N)

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

  • ์žฅ๋ฅด๋ณ„ย secondย ๊ฐ€ ์—†์„ ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์— ๋Œ€ํ•œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ

  • hashMap์˜ย value๊ฐ€ ๊ฐ์ฒด์ผ ๋•Œ ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง€๋Š” ๋Š๋‚Œ ex)ย hash.get(genre).first

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