보라코딩

프로그래머스 자바 :: 신고 결과 받기 본문

프로그래머스 (java)

프로그래머스 자바 :: 신고 결과 받기

new 보라 2024. 6. 6. 20:38

1단계 문제였는데 생각보다 어려웠다.... 

일단 중복을 제거하는 과정에서 HashSet을 사용하는 건 생각해냈고

HashMap을 사용한다는 것도 알았으나

 

getOrDefault를 까먹었었다!!

 

 

나중에 다시 풀어봐야지 ㅜ_ㅜ

 

 

 

 

 

 

 

 

import java.util.*;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        int[] answer = new int[id_list.length];
        
        // 1. 중복제거 (HashSet 사용)
        HashSet<String> uniqueReport = new HashSet(Arrays.asList(report));

        // 2. 신고자 List Map 만들기
        HashMap<String, ArrayList<String>> reporterListMap = new HashMap<>();
        
        for (String str : uniqueReport) {
            String[] split = str.split(" ");
            
            String reporter = split[0]; // 신고한 사람
            String reportee = split[1]; // 신고 당한 사람
            
            // 신고 당한 사람에 대한 신고자 리스트 가져오기, 없으면 새로 생성
            ArrayList<String> reporterList = reporterListMap.getOrDefault(reportee, new ArrayList<>());
            
            reporterList.add(reporter);
            reporterListMap.put(reportee, reporterList);
        }
        
        // 3. 이메일 받을 횟수 저장할 Map 만들기
        HashMap<String, Integer> countEmailMap = new HashMap<>();
        for (ArrayList<String> reporterList : reporterListMap.values()) {
            if (reporterList.size() >= k){
                for (String reporter : reporterList){
                    countEmailMap.put(reporter, countEmailMap.getOrDefault(reporter,0)+1);
                }
            }
        }
        
        // 4. numOfEmailMap을 사용해서 정답 구하기
        for (int i = 0; i < id_list.length; i++) {
            // id_list의 각 유저에 대해 countEmailMap에서 값을 가져오고, 없으면 0을 기본값으로 사용
            answer[i] = countEmailMap.getOrDefault(id_list[i], 0);
        }
        return answer;
    }
}