문제 설명
스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.
속한 노래가 많이 재생된 장르를 먼저 수록합니다.
장르 내에서 많이 재생된 노래를 먼저 수록합니다.
장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.
노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.
나의 풀이 (java)
import java.util.*;
class Solution {
public int[] solution(String[] genres, int[] plays) {
ArrayList<Integer> result = new ArrayList();
// map에 넣기 (장르+재생, 장르별 재생수용)
Map playCountMap = new HashMap<>();
for (int i = 0; i < genres.length; i++) {
playCountMap.put(genres[i], (int)(playCountMap.get(genres[i])==null ? 0:playCountMap.get(genres[i]))+plays[i]);
}
// 정렬(장르별 재생수 합산)
List<Map.Entry<String,Integer>> entryList = new ArrayList<>(playCountMap.entrySet());
Collections.sort(entryList, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
// 장르별 최대 2곡씩 선택
for (Map.Entry<String, Integer> song : entryList) {
int first = 0;
int firstIndex = 0;
int second = 0;
int secondIndex = 0;
for (int i = 0; i < genres.length; i++) {
if(genres[i].equals(song.getKey())){
if(plays[i] > first){
second = first;
secondIndex = firstIndex;
first = plays[i];
firstIndex = i;
} else if(plays[i] > second){
second = plays[i];
secondIndex = i;
}
}
}
result.add(firstIndex);
if(second>0) result.add(secondIndex);
}
// arrList->arr
return result.stream().mapToInt(Integer::intValue).toArray();
}
}
풀이 방법
- HashMap을 사용하여 중복 제거 or 키-값별 카운트 가능
다른사람의 풀이 (java)
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Solution {
public class Music implements Comparable<Music>{
private int played;
private int id;
private String genre;
public Music(String genre, int played, int id) {
this.genre = genre;
this.played = played;
this.id = id;
}
@Override
public int compareTo(Music other) {
if(this.played == other.played) return this.id - other.id;
return other.played - this.played;
}
public String getGenre() {return genre;}
}
public int[] solution(String[] genres, int[] plays) {
return IntStream.range(0, genres.length)
.mapToObj(i -> new Music(genres[i], plays[i], i))
.collect(Collectors.groupingBy(Music::getGenre))
.entrySet().stream()
.sorted((a, b) -> sum(b.getValue()) - sum(a.getValue()))
.flatMap(x->x.getValue().stream().sorted().limit(2))
.mapToInt(x->x.id).toArray();
}
private int sum(List<Music> value) {
int answer = 0;
for (Music music : value) {
answer+=music.played;
}
return answer;
}
}
Godd Idea : 다른사람 : class 나누고, Stream 활용
느낀점
- Comparator 대신 lamda사용
- arrayList<Integer> → array<int>
=> result.stream().mapToInt(Integer::intValue).toArray();
'개발 > 코딩 테스트' 카테고리의 다른 글
[알고리즘] 프로그래머스 > 힙 > 디스크 컨트롤 (0) | 2022.08.16 |
---|---|
[알고리즘] 프로그래머스 > 힙 > 이중우선순위큐 (0) | 2022.08.10 |
[알고리즘] 프로그래머스 > 힙 > 더 맵게 (0) | 2022.08.09 |
[알고리즘] 프로그래머스 > 해시/큐 > 다리를 지나가는 트럭 (0) | 2022.08.08 |
[알고리즘] 프로그래머스 > 스택/큐 > 프린터 (0) | 2022.08.06 |