import java.util.*;
class Solution {
// ์ฅ๋ฅด๋ณ ํ๋ ์ด ํ์๋ฅผ ์์์ผ ํ ๊ฒ
// ํด๋น ์ฅ๋ฅด๋ด์์ ํ๋ ์ด ํ์ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์๋กํ ๊ฒ
public int[] solution(String[] genres, int[] plays) {
//1. ์ฅ๋ฅด๋ณ ์ด ์ฌ์์๋ฅผ map์ ์ด์ฉํด์ ๊ตฌํจ
Map<String, Integer> playsPerGenres = new HashMap<>();
for (int i = 0; i < genres.length; i++) {
playsPerGenres.put(genres[i], playsPerGenres.getOrDefault(genres[i], 0) + plays[i]);
}
//2. ์ฅ๋ฅด๋ณ ์ด ์ฌ์์๋ฅผ ๊ณ์ฐํ playsPerGenres๋ฅผ ์ฌ์ฉํด์ ์ฌ์ํ์๋ฅผ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌํ๋ค.
List<String> orderByPlays = new ArrayList<>();
for (String genresName : playsPerGenres.keySet()) {
orderByPlays.add(genresName);
}
Collections.sort(orderByPlays, (a, b) -> playsPerGenres.get(b) - playsPerGenres.get(a));
//์ฅ๋ฅด๋ณ๋ก ์ ๋ ฌ์ ํ์ผ๋, ์ต๋ 2๊ฐ์ฉ ๋
ธ๋ ๋ฒํธ๋ฅผ ๊ณจ๋ผ album์ ๋ฃ๋๋ค.
List<Integer> album = new ArrayList<>();
//3. ์ฅ๋ฅด๋ณ ์ฌ์์ ๊ธฐ์ค, 1๋ฒ์งธ ์ธ๋ฑ์ค์ 2๋ฒ์งธ ์ธ๋ฑ์ค๋ฅผ ์ฐพ์์ผ ํ๋ค.
for (String genresName : orderByPlays) {
//3.1 ์ฌ์์๊ฐ ๊ฐ์ฅ ๋ง์ ๋ฒํธ๋ฅผ ์ฐพ๋๋ค.
int firstIndex = -1;
for (int i = 0; i < genres.length; i++) {
// ํด๋น ์ฅ๋ฅด๋ฅผ ์ฐพ์ ๊ฒฝ์ฐ
if (genresName.equals(genres[i])) {
//ํ ๋น๋๊ธฐ ์
if (firstIndex == -1) {
firstIndex = i;
} else {
if (plays[firstIndex] < plays[i]) {
firstIndex = i;
}
}
}
}
//3.2 ์ฌ์์๊ฐ ๋๋ฒ์งธ๋ก ๋ง์ ๋ฒํธ๋ฅผ ์ฐพ๋๋ค.
int secondIndex = -1;
for (int i = 0; i < genres.length; i++) {
if (genresName.equals(genres[i]) && firstIndex != i) {
if (secondIndex == -1) {
secondIndex = i;
} else {
if (plays[secondIndex] < plays[i]) {
secondIndex = i;
}
}
}
}
album.add(firstIndex);
//2๋ฒ์งธ ๊ณก์ ์ฐพ์ ๊ฒฝ์ฐ๋ง ์ถ๊ฐ
if (secondIndex != -1) {
album.add(secondIndex);
}
}
// ๋ฐฐ์ด๋ก ๋ณํ ํ ๋ฐํํ๋ค.
int[] answer = new int[album.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = album.get(i);
}
return answer;
}
}
3๋ฒ ๊ณผ์ ์์, ์ค๋ณต๋๋ ์ฝ๋๊ฐ ์์ด์ ์ต๋ํ ๊ฐ๊ฒฐํ ๋ก์ง์ผ๋ก ์์ฑํด๋ณด๋ คํ๋๋ฐ ์ ์ํ๋ ค์
๊ทธ๋ฅ ๋๋ฒ for๋ฌธ์ ์จ์ ๊ตฌํ๋ค.
๋ฆฌํฉํ ๋ง์ ํด๋ด์ผ๊ฒ ๋ค.