Hash를 사용하는 문제였다. LinkedHashMap, HashSet을 사용해 풀었다.
int[] answer = {};
answer = new int[id_list.length];
HashMap<String, HashSet<String>> reportLog = new HashMap<>();
Arrays.stream(id_list).forEach(id -> reportLog.put(id, new HashSet<>()));
우선, answer를 초기화하고, 신고 기록을 담을 HashMap을 만들었다. reportLog는 key로 id를 가지고, value로 해당 id를 신고한 id들을 가진다. value를 HashSet으로 한 이유는, 중복 신고가 없기 때문이다.
Arrays.stream(report).forEach(log -> {
reportLog.get(log.split(" ")[1]).add(log.split(" ")[0]);
});
reportLog에 값을 넣어 준다. report는 공백을 기준으로 나누어져 있으므로, split을 통해 적절하게 처리해 준다. 해당 코드는 모든 id를 돌며 해당 id에 대한 신고자들을 추가해 주는 코드이다.
LinkedHashMap<String, Integer> mail = new LinkedHashMap<>();
Arrays.stream(id_list).forEach(id -> mail.put(id, 0));
이제 mail을 보낼 차례이다. 우선, id당 mail을 몇 번 받았는지 저장해줄 LinkedHashMap<String, Integer> mail을 만든다. LinkedHashMap을 사용한 이유는 id_list에 담긴 id 순서대로 return 해야 하기 때문이다. mail에 id 순서대로 받은 mail을 넣어 주고, answer에 다시 mail을 넣어 줄 것이다. id_list에 저장되어 있는 id들을 순서대로 mail에 넣어서 초기화해 주었다.
reportLog.forEach((key, value) -> {
if(value.size() >= k){
value.forEach(v -> {
mail.put(v, mail.get(v) + 1);
});
}
});
reportLog를 순회하며 k번 이상 신고를 받은 id를 찾고, 해당 id를 신고한 사람들에게 메일을 보낸다.
for(int i = 0; i<id_list.length; i++){
answer[i] = mail.get(id_list[i]);
}
return answer;
answer에 넣어준 후 return 하면 끝이다.
프로그래머스는 처음 풀어 봐서 풀고 제출하는 데에서 애를 먹었다...
결과 코드
import java.util.*;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = {};
answer = new int[id_list.length];
HashMap<String, HashSet<String>> reportLog = new HashMap<>();
Arrays.stream(id_list).forEach(id -> reportLog.put(id, new HashSet<>()));
Arrays.stream(report).forEach(log -> {
reportLog.get(log.split(" ")[1]).add(log.split(" ")[0]);
});
LinkedHashMap<String, Integer> mail = new LinkedHashMap<>();
Arrays.stream(id_list).forEach(id -> mail.put(id, 0));
reportLog.forEach((key, value) -> {
if(value.size() >= k){
value.forEach(v -> {
mail.put(v, mail.get(v)+1);
});
}
});
for(int i = 0; i<id_list.length; i++){
answer[i] = mail.get(id_list[i]);
}
return answer;
}
}