https://school.programmers.co.kr/learn/courses/30/lessons/92334
1. HashMap에 유저별 순서를 저장. idMap.get(이름) = 정답배열의 인덱스
//유저별 순서
HashMap<String, Integer> idMap = new LinkedHashMap<>();
//유저별 자신을 신고한 유저
HashMap<String, HashSet<String>> map = new HashMap<>();
for(int i = 0; i < id_list.length; i++) {
idMap.put(id_list[i], i);
map.put(id_list[i], new HashSet<>());
}
2. HashSet이란? 중복 X, 순서 X
-> 자신을 신고한 유저를 중복 없이 담을 수 있다.
//선언
HashSet<Integer> set = new HashSet<Integer>();
//값 추가
set.add(1);
set.add(2);
set.add(2);
set.add(3);
System.out.println(set); //-> [1, 2, 3]
//값 삭제
set.remove(1);
System.out.println(set); // -> [2, 3]
//전체 삭제
set.clear();
System.out.println(set); //->[]
최종 풀이
public class Test {
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = new int[id_list.length];
//유저별 순서
HashMap<String, Integer> idMap = new LinkedHashMap<>();
//유저별 자신을 신고한 유저
HashMap<String, HashSet<String>> map = new HashMap<>();
for(int i = 0; i < id_list.length; i++) {
idMap.put(id_list[i], i);
map.put(id_list[i], new HashSet<>());
}
for(String s : report) {
String[] str = s.split(" ");
map.get(str[1]).add(str[0]);
}
for(int i = 0; i < id_list.length; i++) {
HashSet<String> send = map.get(id_list[i]);
if(send.size() >= k) {
for(String name : send) {
answer[idMap.get(name)]++;
}
}
}
return answer;
}
public static void main(String[] args) {
Test t = new Test();
String[] list = {"muzi", "frodo", "apeach", "neo"};
String[] report = {"muzi frodo","apeach frodo","frodo neo","muzi neo","apeach muzi"};
t.solution(list, report, 2);
}
}
'코딩테스트 > programmers' 카테고리의 다른 글
[2019 카카오 개발자 겨울 인턴십]튜플 - java (0) | 2022.08.16 |
---|---|
올바른 괄호 - java (0) | 2022.08.16 |
로또의 최고 순위와 최저 순위 (0) | 2022.06.12 |
[array03]H-Index (0) | 2022.06.10 |
[array02]가장 큰 수 (0) | 2022.06.10 |