프로그래머스-베스트앨범

EaseTheWorld·2020년 7월 21일
0

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

HashMap, Sort 가 섞여있는 문제다. top 2만 구하면 되므로 정렬까진 필요없고 O(n)이면 된다. python보다가 java를 보니까 자잘한 array, list 변환들때문에 코드가 좀 지저분하다.
전체 Time은 장르갯수가 n이라 할때 O(nlogn). sort 대신 PriorityQueue를 쓴다해도 nlogn이다.

    public int[] solution(String[] genres, int[] plays) {
        HashMap<String, int[]> map = new HashMap<>();
        for (int i=0; i<genres.length; ++i) {
            int[] genre = map.getOrDefault(genres[i], new int[] {0, -1, -1});
            // 0 : total play, 1 : max plays, 2 : second plays
            genre[0] += plays[i];
            if (genre[1] == -1 || plays[i] > plays[genre[1]]) {
                genre[2] = genre[1];
                genre[1] = i;
            } else if (genre[2] == -1 || plays[i] > plays[genre[2]]) {
                genre[2] = i;
            }
            map.put(genres[i], genre);
        }
        ArrayList<int[]> genres_sorted = new ArrayList<>(map.values());
        Collections.sort(genres_sorted, Comparator.comparing(g->-g[0]));
        ArrayList<Integer> result = new ArrayList<>();
        for (int[] genre : genres_sorted) {
            result.add(genre[1]);
            if (genre[2] != -1)
                result.add(genre[2]);
        }
        return result.stream().mapToInt(i->i).toArray();
    }

0개의 댓글