미소의 세상

[알고리즘] 신고 결과 받기 본문

알고리즘/알고리즘 풀이

[알고리즘] 신고 결과 받기

짱미소 2022. 4. 20. 23:00

https://programmers.co.kr/learn/courses/30/lessons/92334?language=java 

 

코딩테스트 연습 - 신고 결과 받기

문제 설명 신입사원 무지는 게시판 불량 이용자를 신고하고 처리 결과를 메일로 발송하는 시스템을 개발하려 합니다. 무지가 개발하려는 시스템은 다음과 같습니다. 각 유저는 한 번에 한 명의

programmers.co.kr

 

import java.util.*;
class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {

        int idLength = id_list.length;
        int reportLength = report.length;

        int[] answer = new int[idLength];
        // key : 신고인, value : 피 신고인
        Map<String, List> reportMap = new HashMap<>();
        // key : 피 신고인, value : 신고당한 횟수
        Map<String, Integer> reportCnt = new HashMap<>();
        String reportList;

        // 2개의 HashMap의 초기화 작업
        for (int i = 0; i < idLength; i++) {
            reportMap.put(id_list[i], null);
            reportCnt.put(id_list[i], 0);
        }
        for (int i = 0; i < reportLength; i++) {
            // report 1개를 받아옴
            reportList = report[i];
            // 신고인과 피 신고인으로 나눔
            String[] sepReport = reportList.split(" ");

            // 이미 존재하는 list가 없으면 새로 만들고 아니면 기존 리스트에 피 신고자 명단을 추가
            if (reportMap.get(sepReport[0]) == null) {
                List<String> newList = new ArrayList<>();
                newList.add(sepReport[1]);
                reportMap.put(sepReport[0], newList);
            } else {
                List<String> existList = reportMap.get(sepReport[0]);
                // 중복이 있다면 넣지 않음
                if (!existList.contains(sepReport[1]))
                    existList.add(sepReport[1]);
            }
        }
        // System.out.println(reportMap);
        // 반복하면서 각 멤버들의 신고당한 횟수를 저장함
        for (int i = 0; i < idLength; i++) {
            List<String> list = reportMap.get(id_list[i]);
            if (list != null) {
                for (String respondent: list) {
                    int count = reportCnt.get(respondent);
                    count++;
                    reportCnt.put(respondent, count);
                }
            }
        }
        // System.out.println(reportCnt);
        for (int i = 0; i < idLength; i++) {
            //  특정 인물(id_list[i]가 신고인)이 신고당한 횟수가 k 이상이면
            if (reportCnt.get(id_list[i]) >= k) {
                for (int j = 0; j < idLength; j++) {
                    // 피 신고인의 명단을 처음부터 받아옴
                    List<String> list = reportMap.get(id_list[j]);
                    if (list != null) {
                        // 만약 정지사유가 되는 특정인물이 신고인(id_list[i])이 신고한 리스트에 들어있다면
                        // 신고인이 메일을 받아야 하므로 answer에서 해당 인덱스의 정수값 1 증가
                        if(list.contains(id_list[i]))
                            answer[j]++;
                    }
                }
            }
        }
        return answer;
    }
}
Comments