💜 코딩테스트/💜프로그래머스
(JAVA) 99클럽 코테 스터디 1일차 TIL [Stream().mapToInt와 toArray의 차이] / 프로그래머스 [베스트앨범]
eyes from es
2024. 5. 20. 23:18
728x90
반응형
#HashMap #클래스 #Comparable #Stream #mapToInt
toArray() vs mapToInt(Integer::inValue).toArray() 차이
toArray(): 반환값이 Object라서 형변환시 int[]이런 식으로 특정 형변환이 보장X
import java.util.*;
class Solution {
static class playListManager implements Comparable<playListManager> {
int count;
List<playOfSong> playList;
public playListManager() {
this.count = 0;
this.playList = new ArrayList<>();
}
public playListManager(String genre, playOfSong pl) {
this();
addPlayCount(pl.index, pl.playCount);
}
public void addPlayCount(int index, int playCount) {
this.count += playCount;
this.playList.add(new playOfSong(index, playCount));
}
public void sortPlayList() {
Collections.sort(this.playList);
}
@Override
public int compareTo(playListManager o) {
return o.count - this.count;
}
}
static class playOfSong implements Comparable<playOfSong> {
int index;
int playCount;
public playOfSong(int index, int playCount) {
this.index = index;
this.playCount = playCount;
}
@Override
public int compareTo(playOfSong o) {
if (this.playCount != o.playCount) {
return o.playCount - this.playCount;
} else {
return this.index - o.index;
}
}
}
public int[] solution(String[] genres, int[] plays) {
HashMap<String, playListManager> play = new HashMap<>();
for (int i = 0; i < genres.length; i++) {
String genre = genres[i];
if(!play.containsKey(genre)) {
play.put(genre, new playListManager());
}
play.get(genre).addPlayCount(i, plays[i]);
}
List<Integer> result = new ArrayList<>();
List<playListManager> genreList = new ArrayList<>(play.values());
Collections.sort(genreList);
for(playListManager genre : genreList) {
genre.sortPlayList();
for(int i = 0; i<genre.playList.size(); i++){
if(i==2) break;
result.add(genre.playList.get(i).index);
}
}
return result.stream().mapToInt(Integer::intValue).toArray();
}
}
회고 🤔
- 나는 class를 2개를 했는데 다른 코드를 보니까
Class Music implements Comparable<Music>{
String genre;
int index;
int play;
}
이런 식으로 하나의 class를 만들고 정렬 조건은 클래스 내부에 넣었다.
1. Map<String, Integer> 장르, totalPlay
그리고 for문을 돌면서 해당 장르의 play횟수를 Map에 저장
-> keySet으로 가져와서 totalPlay 갯수 내림차순 정렬
2. List에 add로 Music(genres[i], index, plays[i])
1. Map에 contain 여부 확인
있으면 List에 추가
2. 없으면 새로운 List에 추가
3. 정렬
4. 최대 2개씩
728x90
반응형