Notice
Recent Posts
Recent Comments
Link
ยซ   2024/12   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ฒ ์ŠคํŠธ์•จ๋ฒ” (js) ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ฒ ์ŠคํŠธ์•จ๋ฒ” (js)

Lennon 2021. 10. 26. 17:32
728x90
๋ฐ˜์‘ํ˜•

https://programmers.co.kr/learn/courses/30/lessons/42579?language=javascript 

 

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

์ŠคํŠธ๋ฆฌ๋ฐ ์‚ฌ์ดํŠธ์—์„œ ์žฅ๋ฅด ๋ณ„๋กœ ๊ฐ€์žฅ ๋งŽ์ด ์žฌ์ƒ๋œ ๋…ธ๋ž˜๋ฅผ ๋‘ ๊ฐœ์”ฉ ๋ชจ์•„ ๋ฒ ์ŠคํŠธ ์•จ๋ฒ”์„ ์ถœ์‹œํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค. ๋…ธ๋ž˜๋Š” ๊ณ ์œ  ๋ฒˆํ˜ธ๋กœ ๊ตฌ๋ถ„ํ•˜๋ฉฐ, ๋…ธ๋ž˜๋ฅผ ์ˆ˜๋กํ•˜๋Š” ๊ธฐ์ค€์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์†ํ•œ ๋…ธ๋ž˜๊ฐ€

programmers.co.kr

 

function solution(genres, plays) {
    const set = new Set(genres);
    const UniqueGenres = [...set];
    
    const playCount = UniqueGenres.map((v) => {
        const play = genres.reduce((prev,cur,idx) => {
            if(cur === v) prev += plays[idx];
            return prev;
        },0)
        
        return [v, play];
    })

    playCount.sort((a,b) => b[1]-a[1]);
    
    const genresPlays = genres.map((v, i) => [v, plays[i], i])

    genresPlays.sort((a,b) => b[1]-a[1]);

    let answer = [];
    for(let i = 0; i < playCount.length; i++){
        let count = 0;
        for(let j = 0; j < genresPlays.length; j++){
            if(playCount[i][0] === genresPlays[j][0]){
                count++;
                answer.push(genresPlays[j][2]);
                if(count===2) break;
            }
        }
    }
    return answer;
}

 

ํ•ด์‹œ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ์ด๋‹ค.

 

์ฒ˜์Œ์— reduce, map์„ ์ด์šฉํ•˜์—ฌ ํ’€์—ˆ์ง€๋งŒ, ๋งŽ์•„๋„ ์žฅ๋ฅด๋ณ„ ๋งŽ์ด ์žฌ์ƒ๋œ ์Œ์•… 2๊ฐœ๋งŒ ์ฐพ์œผ๋ฉด ๋˜๊ธฐ๋•Œ๋ฌธ์—

 

ํšจ์œจ์ ์œผ๋กœ ๋™์ž‘ํ•  ์ˆ˜ ์žˆ๋„๋ก break๋ฅผ ๊ฑธ ์ˆ˜ ์žˆ๊ฒŒ for๋ฌธ์„ ์ด์šฉํ•˜์˜€๋‹ค. 

728x90
๋ฐ˜์‘ํ˜•
Comments