728x90
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
복잡하지만 HashMap과 list, 우선순위 큐 Comparator 정렬로 조건에 맞게 정렬만 해주면 된다.
유념해야할 사항은 한 장르에는 최대 2곡까지만 들어갈 수 있다는 것!
전체코드
import java.io.*;
import java.util.*;
class Solution {
public List<Integer> solution(String[] genres, int[] plays) {
HashMap<String, Integer> map = new HashMap<>();
for(int i=0; i<genres.length; i++){
if(!map.containsKey(genres[i])){
map.put(genres[i], plays[i]);
}else{
map.put(genres[i], map.get(genres[i])+plays[i]);
}
}
List<String> list = new ArrayList<>();
for(String key : map.keySet()){
list.add(key);
}
Collections.sort(list, new Comparator<>(){
public int compare(String o1, String o2){
return map.get(o2) - map.get(o1);
}
});
int count[] = new int[list.size()];
PriorityQueue<String[]> pq = new PriorityQueue<>(new Comparator<>(){
public int compare(String[] o1, String[] o2){
if(list.indexOf(o1[0]) < list.indexOf(o2[0])){
return -1;
}else if(list.indexOf(o1[0]) > list.indexOf(o2[0])){
return 1;
}else{
if(Integer.valueOf(o1[1]) > Integer.valueOf(o2[1])){
return -1;
}else if(Integer.valueOf(o1[1]) < Integer.valueOf(o2[1])){
return 1;
}else{
if(Integer.valueOf(o1[2]) > Integer.valueOf(o2[2])){
return 1;
}else if(Integer.valueOf(o1[2]) < Integer.valueOf(o2[2])){
return -1;
}else{
return 0;
}
}
}
}
});
for(int i=0; i<genres.length; i++){
String tmp[] = {genres[i], plays[i]+"", i+"", list.indexOf(genres[i])+""};
pq.offer(tmp);
}
List<Integer> answer = new ArrayList<>();
while(!pq.isEmpty()){
String now[] = pq.poll();
if(count[Integer.valueOf(now[3])] < 2){
count[Integer.valueOf(now[3])]++;
answer.add(Integer.valueOf(now[2]));
}
}
return answer;
}
}
728x90
'코테 > Algorithm' 카테고리의 다른 글
[Programmers] 숫자 게임 (JAVA) (0) | 2024.08.06 |
---|---|
[BOJ] 1105: 팔 (JAVA) (0) | 2024.08.04 |
[Programmers] 최고의 집합 (JAVA) (0) | 2024.08.01 |
[Programmers] 등굣길 (JAVA) (0) | 2024.07.30 |
[Programmers] 단어 변환 (JAVA) (0) | 2024.07.29 |