08.27.(토)
무작정 작동하게끔만 풀어봤다.
import java.util.HashSet;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
// 0. report에서 중복 제거하기
HashSet<String> report_unique = new HashSet<>(Arrays.asList(report));
// System.out.println("중복을 제거한 report: " + report_unique);
// 1. report에 등장한 아이디별로 신고당한 횟수 세기
HashMap<String, Integer> reported_count = new HashMap<>(report.length);
LinkedHashMap<String, ArrayList<String>> report_map = new LinkedHashMap<>(report.length);
for (String pair : report_unique) {
String reporter_id = pair.split(" ")[0];
String reported_id = pair.split(" ")[1];
// 1.1 신고자:[신고당한1, 신고당한2,...] 리스트 만들기
if (report_map.containsKey(reporter_id)) {
report_map.get(reporter_id).add(reported_id);
} else {
report_map.put(reporter_id, new ArrayList<String>(Arrays.asList(reported_id)));
}
// 1.2 신고당한 id별로 횟수 세기
if (reported_count.containsKey(reported_id)) {
reported_count.put(reported_id, reported_count.get(reported_id) + 1);
} else {
reported_count.put(reported_id, 1);
}
}
// System.out.println("유저별 신고한 ID 리스트: " + report_map);
// System.out.println("유저별 신고당한 횟수: " + reported_count);
// 2.0 정지당한 자:
ArrayList<String> banned = new ArrayList<>();
for (String user : reported_count.keySet()) {
if (reported_count.get(user) >= k) {
banned.add(user);
}
}
// System.out.println("정지당한 유저: " + banned);
// 2. 신고한 자가 정지된 신고자를 몇이나 가지고 있는지 report_map에서 조사.
int[] answer = new int[id_list.length];
for (int i = 0; i < id_list.length; i++) {
String user = id_list[i];
if (!report_map.containsKey(user)) {
answer[i] = 0;
} else {
ArrayList<String> intersection = new ArrayList<>(report_map.get(user));
intersection.retainAll(banned); //신고자별 신고한 id ArryaList와 banned의 ArrayList의 교집합
answer[i] = intersection.size();
}
}
return answer;
}
}
새롭게 찾아 쓴(a.k.a. 구글링한) 코드:
- 중복 제거할 때 HashSet에 배열 넣어 만들기.
- HashMap 만들 때 길이를 인자로 넘겨줄 수 있다.
- Map 계열의 메소드들:
- 넣을 땐 put(키, 값)
- 찾을 땐 get(키)
- 키 전체를 루프 돌아야 할 땐 keySet()
- 특정 키가 들었는지 검사할 땐 containsKey(키).
- List 계열의 메소드들:
- 넣을 땐 add(값)
- 찾을 땐 get(인덱스)
- 교집합만 남길 때 유용한 retainAll(리트스)
- 길이 구할 땐 .length 아니고 .size()
아쉬운 점:
- Arrays.asList()가 받는 인자와 리턴값이 정확히 어떻게 되는지, 그래서 HashSet과 ArrayList에는 어떻게 들어갈 수 있었는지 알아봐야겠다.
- 기능별로 메소드를 따로 만들어볼 수도 있었을 것 같다.
며칠 이론만 공부했더니, 지금은 코드를 자세히 다시 뜯어보기보다 문제를 더 풀어서 이미 알고 있는 것에 더 익숙해지고 싶다. 몇 주 뒤에는 위의 코드를 더 잘 고쳐볼 수 있지 않을까?