습관제작소
23-01-02 코딩테스트 해쉬#6 (신고 결과 받기) 본문
Hash를 활용한 Solution
+문제해석
- 중복 제거
Hash set을 사용하여 report의 중복된 정보를 제거한다. - 신고자 목록
Hash로 각 사용자를 신고한 사람들의 목록을 관리한다. - 신고한 사용자
정지된 사용자를 신고한 사용자에게 알려주고, 이 정보를 Hash로 정리
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
class Solution09 {
public int[] solution(String[] id_list, String[] report, int k){
int[] answer = new int [id_list.length];
// 1. 중복 제거
HashSet<String> reportSet = new HashSet<String>();
for(String rep : report){
reportSet.add(rep);
}
// 2. notifyListHash만들기
HashMap<String, ArrayList<String>> notifyListHash=new HashMap<>();
for(String rep : reportSet){
int blankIdx = rep.indexOf(" ");
String reporter = rep.substring(0, blankIdx);
String reportee = rep.substring(blankIdx+1);
ArrayList<String> reporterList = notifyListHash.getOrDefault(reportee, null);
if(reporterList == null){
reporterList = new ArrayList<>();
}
reporterList.add(reporter);
notifyListHash.put(reportee, reporterList);
}
// 3. notifyListHash를 기반으로 reporterHash 만들기
HashMap<String, Integer> reporterHash = new HashMap<>();
for(ArrayList<String> notifyList : notifyListHash.values()){
if(notifyList.size()>=k){
for(String reporter : notifyList){
reporterHash.put(reporter, reporterHash.getOrDefault(reporter,0)+1);
}
}
}
// 4. reporterHash를 기반으로 answer 배열을 채운다.
for(int i=0; i<id_list.length;i++){
answer[i]=reporterHash.getOrDefault(id_list,0);
}
return answer;
}
public static void main(String[] args) {
Solution09 sol= new Solution09();
String [] id_list = {"muzi", "frodo", "apeach","neo"};
String [] report = {"muzi frodo", "apeach frodo", "frodo neo", "muzi neo", "apeach muzi"};
int k =2;
// String [] id_list = {"con", "ryan"};
// String [] report = {"ryan con", "ryan con", "ryan con", "ryan con", "apeach muzi"};
// int k =3;
sol.solution(id_list, report, k);
}
}
'Code Question > 코드 문제' 카테고리의 다른 글
22-12-20 코딩테스트 해쉬#5 (순위 검색) (0) | 2022.12.20 |
---|---|
22-12-19 코딩테스트 해쉬#4 (메뉴 리뉴얼) (0) | 2022.12.19 |
22-12-17 코딩테스트 해쉬#3 (위장) (0) | 2022.12.17 |
22-12-16 코딩테스트 해쉬#2 (전화번호 목록) (0) | 2022.12.16 |
22-12-15 코딩테스트 해쉬#1 (완주하지 못한 선수) (0) | 2022.12.15 |
Comments