-
[프로그래머스] 베스트앨범Coding 2021. 6. 14. 06:42
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; class Solution { public int[] solution(String[] genres, int[] plays) { List<Integer> answer = new ArrayList<>(); Map<String, Integer> hm = new HashMap<>(); for (int i = 0; i < genres.length; i++) { hm.put(genres[i], hm.getOrDefault(genres[i], 0) + plays[i]); } List<String> al = new ArrayList<String>(hm.keySet()); Collections.sort(al, (o1, o2) -> hm.get(o2) - hm.get(o1)); for (int i = 0; i < al.size(); i++) { String TempGenres = al.get(i); int firstIdx = 0; int secondIdx = 0; int maxplay = 0; for (int j = 0; j < plays.length; j++) { if (genres[j].equals(TempGenres)) { if (plays[j] > maxplay) { maxplay = plays[j]; firstIdx = j; } } } maxplay = -1; for (int j = 0; j < plays.length; j++) { if (genres[j].equals(TempGenres)) { if (j != firstIdx && plays[j] > maxplay) { maxplay = plays[j]; secondIdx = j; } } } answer.add(firstIdx); if (maxplay != -1) { answer.add(secondIdx); } } return answer.stream().mapToInt((s) -> s.intValue()).toArray(); } }
처음 코드를 짤때는
hm.put(genres[i], hm.getOrDefault(genres[i], plasy[i]) + plays[i]); 로 했었는데.. 그러면 안됨
왜? 제일 끝 "+ plays[i]" 로 인해 디폴트일 경우에 알아서 들어감...
처음 생각대로하면 두번 더해주는 꼴이였음.. 그래서 아래와 같이 해야함
hm.put(genres[i], hm.getOrDefault(genres[i], 0) + plays[i]);
campareTo메소드..
Collections.sort(al, (o1, o2) -> hm.get(o2) - hm.get(o1)); 말고
Collections.sort(al, (o1,o2)->(hm.get(o2).compareTo(hm.get(o1)))); 도 가능
두번째 인덱스를 구하는 과정을 조금 더 간편하게 할 순 없을까 고민을 해봤는데
내 머리로는 아직 잘 모르겠음
'Coding' 카테고리의 다른 글
[프로그래머스]프린터 (0) 2021.06.18 [프로그래머스]기능개발 (0) 2021.06.16 [프로그래머스] 전화번호 목록 (0) 2021.06.12 프로그래머스(주식가격) (0) 2020.08.08 프로그래머스(완주하지 못한 선수) (0) 2020.08.08