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
๋ฐ์ํ