๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/์ž๋ฃŒ๊ตฌ์กฐ & ์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ฒ ์ŠคํŠธ์•จ๋ฒ” (Java)

by 1mj 2021. 11. 3.

https://programmers.co.kr/learn/courses/30/lessons/42579

 

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

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

programmers.co.kr

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๊ณ ๋“์  Kit ๋ฒ ์ŠคํŠธ์•จ๋ฒ” ๋ฌธ์ œ ํ’€์ด์ด๋‹ค.

๋ฌธ์ œ๊ฐ€ ๊น”๋”ํ•˜๊ฒŒ ํ’€๋ฆฌ์ง€๋Š” ์•Š์•˜๋Š”๋ฐ ์ •๋ ฌ๋ฒ•์„ ๋ฐฐ์šฐ๋Š”๋ฐ ๋„์›€์ด ๋˜์—ˆ๋˜ ๋ฌธ์ œ์ด๋‹ค.

 

import java.util.*;

class Solution {
    public int[] solution(String[] genres, int[] plays) {
        
        // ์žฅ๋ฅด, ์žฅ๋ฅด๋ณ„ ์ด ์žฌ์ƒํšŸ์ˆ˜
        Map<String, Integer> playsMap = new HashMap<>();
        for (int i = 0; i < genres.length; i++) {
            playsMap.put(genres[i], playsMap.getOrDefault(genres[i], 0) + plays[i]);
        }

        // ์žฅ๋ฅด, ์žฅ๋ฅด๋ณ„ ์ด ์žฌ์ƒํšŸ์ˆ˜ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ (๊ฐ€์žฅ ๋งŽ์ด ์žฌ์ƒ๋œ ์žฅ๋ฅด -> ๊ฐ€์žฅ ์ ๊ฒŒ ์žฌ์ƒ๋œ ์žฅ๋ฅด)
        List<String> genresList = new ArrayList<>(playsMap.keySet());
        Collections.sort(genresList, (o1, o2) -> (playsMap.get(o2).compareTo(playsMap.get(o1))));

        // ์žฅ๋ฅด, ์žฅ๋ฅด ๋‚ด ๋…ธ๋ž˜ ๊ณ ์œ ๋ฒˆํ˜ธ ๋ชฉ๋ก
        Map<String, List<Integer>> numMap = new HashMap<>(); 
        for (int i = 0; i < genres.length; i++) {
            List<Integer> temp = new ArrayList<>();
            if (numMap.containsKey(genres[i])) {
                temp = numMap.get(genres[i]);
                temp.add(i);
                numMap.put(genres[i], temp);
            } else {
                temp.add(i);
                numMap.put(genres[i], temp);
            }
        }
        
        List<Integer> result = new ArrayList<>();
        for (String genre : genresList) {
            int idx = 0;
            // ์žฅ๋ฅด ๋‚ด์—์„œ ๋งŽ์ด ์žฌ์ƒ๋œ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌ (๊ฐ™์„ ๊ฒฝ์šฐ ๊ณ ์œ  ๋ฒˆํ˜ธ๊ฐ€ ๋‚ฎ์€ ๊ฑฐ ๋จผ์ €)
            Collections.sort(numMap.get(genre), (o1, o2) -> (plays[o1] == plays[o2] ? o1 - o2 : plays[o2] - plays[o1]));
            for (int n : numMap.get(genre)) {
                if (idx < 2) {
                    result.add(n);  // ์žฅ๋ฅด ๋‹น 2๊ฐœ๋งŒ ๊ฒฐ๊ณผ์— ์ถ”๊ฐ€
                }
                idx++;
            }
        }
        
        return result.stream().mapToInt(i -> i).toArray();
    }
}

 

 

๋Œ“๊ธ€