오늘은 여기까지

[프로그래머스] 베스트 앨범 - Java 자바 본문

Problem Solving

[프로그래머스] 베스트 앨범 - Java 자바

dev-99 2024. 10. 29. 09:30

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

사용개념: 해시

 

 

1. 노래 정보를 하나의 객체로 관리한다.

class Song {
	int id;
    int plays;
        
    Song(int id, int plays) {
    	this.id = id;
        this.plays = plays;
    }
}

 

 

2. 데이터 정리

장르별 총 재생횟수를 저장할 맵 하나, 장르별 노래 정보 (고유번호, 재생횟수) 저장할 맵 하나가 필요하다.

전체를 순회하면서 데이터를 정리한다.

HashMap<String, Integer> playByGenre = new HashMap<>(); // 장르별 총 재생횟수
HashMap<String, ArrayList<Song>> playlist = new HashMap<>(); // 장르별 노래 목록
int num = genres.length; // 전체 노래 개수

for (int i=0; i < num; i++) {
	String genre = genres[i];
    int play = plays[i];
            
	// 장르별 재생횟수 누적합 저장
    playByGenre.put(genre, playByGenre.getOrDefault(genre, 0) + play);
            
	// 장르별 노래 정보 저장
	if (!playlist.containsKey(genre)) {
		playlist.put(genre, new ArrayList<>());
	}
    playlist.get(genre).add(new Song(i, play));
}

 

 

3. 장르를 총 재생횟수를 기준으로 정렬한다.

List<String> sortedGenres = new ArrayList<>(playByGenre.keySet());
sortedGenres.sort((g1, g2) -> playByGenre.get(g2).compareTo(playByGenre.get(g1)));
// Integer 객체 비교라 compareTo 사용

 

 

4. 장르 내 노래를 재생횟수(내림차순), 고유번호(오름차순)을 기준으로 정렬한다.

for (String genre : sortedGenres) {
	ArrayList<Song> songs = playlist.get(genre);

	songs.sort((s1, s2) -> {
		if (s1.plays != s2.plays) {
			return s2.plays - s1.plays; // 정수 비교라 오버플로우 걱정 없어서 빼기 연산 사용
		}
		return s1.id - s2.id;
	});

	for (int i=0; i < Math.min(2, songs.size()); i++) {
		answer.add(songs.get(i).id);
	}
}

 

 

전체코드

더보기
import java.util.*;

class Solution {
    class Song {
        int id;
        int plays;
        
        Song(int id, int plays) {
            this.id = id;
            this.plays = plays;
        }
    }
    
    public int[] solution(String[] genres, int[] plays) {
        HashMap<String, Integer> playByGenre = new HashMap<>(); // 장르별 총 재생횟수
        HashMap<String, ArrayList<Song>> playlist = new HashMap<>(); // 장르별 노래 목록
        int num = genres.length; // 전체 노래 개수

        for (int i=0; i < num; i++) {
            String genre = genres[i];
            int play = plays[i];
            
            // 장르별 재생횟수 누적합 저장
            playByGenre.put(genre, playByGenre.getOrDefault(genre, 0) + play);
            
            // 장르별 노래 정보 저장
            if (!playlist.containsKey(genre)) {
                playlist.put(genre, new ArrayList<>());
            }
            playlist.get(genre).add(new Song(i, play));
        }

        // 장르를 총 재생횟수를 기준으로 정렬
        List<String> sortedGenres = new ArrayList<>(playByGenre.keySet());
        sortedGenres.sort((g1, g2) -> playByGenre.get(g2).compareTo(playByGenre.get(g1)));

        ArrayList<Integer> answer = new ArrayList<>();

        // 장르 내 노래를 재생횟수(내림차순), 고유번호(오름차순) 기준으로 정렬
        for (String genre : sortedGenres) {
            ArrayList<Song> songs = playlist.get(genre);

            songs.sort((s1, s2) -> {
                if (s1.plays != s2.plays) {
                    return s2.plays - s1.plays; // 내림차순
                }
                return s1.id - s2.id; // 오름차순
            });

            for (int i=0; i < Math.min(2, songs.size()); i++) {
                answer.add(songs.get(i).id);
            }
        }

        return answer.stream().mapToInt(i->i).toArray();
    }
}