알고리즘/알고리즘 풀이

[프로그래머스_1] 신고 결과 받기 JAVA

데부한 2022. 3. 27. 01:25
반응형

 

 

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

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

programmers.co.kr

 

 

문제

신입사원 무지는 게시판 불량 이용자를 신고하고 처리 결과를 메일로 발송하는 시스템을 개발하려 합니다. 무지가 개발하려는 시스템은 다음과 같습니다.

  • 각 유저는 한 번에 한 명의 유저를 신고할 수 있습니다.
    • 신고 횟수에 제한은 없습니다. 서로 다른 유저를 계속해서 신고할 수 있습니다.
    • 한 유저를 여러 번 신고할 수도 있지만, 동일한 유저에 대한 신고 횟수는 1회로 처리됩니다.
  • k번 이상 신고된 유저는 게시판 이용이 정지되며, 해당 유저를 신고한 모든 유저에게 정지 사실을 메일로 발송합니다.
    • 유저가 신고한 모든 내용을 취합하여 마지막에 한꺼번에 게시판 이용 정지를 시키면서 정지 메일을 발송합니다.

 

 

제한사항

  • 2 ≤ id_list의 길이 ≤ 1,000
    • 1 ≤ id_list의 원소 길이 ≤ 10
    • id_list의 원소는 이용자의 id를 나타내는 문자열이며 알파벳 소문자로만 이루어져 있습니다.
    • id_list에는 같은 아이디가 중복해서 들어있지 않습니다.
  • 1 ≤ report의 길이 ≤ 200,000
    • 3 ≤ report의 원소 길이 ≤ 21
    • report의 원소는 "이용자id 신고한id"형태의 문자열입니다.
    • 예를 들어 "muzi frodo"의 경우 "muzi"가 "frodo"를 신고했다는 의미입니다.
    • id는 알파벳 소문자로만 이루어져 있습니다.
    • 이용자id와 신고한id는 공백(스페이스)하나로 구분되어 있습니다.
    • 자기 자신을 신고하는 경우는 없습니다.
  • 1 ≤ k ≤ 200, k는 자연수입니다.
  • return 하는 배열은 id_list에 담긴 id 순서대로 각 유저가 받은 결과 메일 수를 담으면 됩니다.

 

반응형

 

문제를 보며 가장 중요한 부분으로 생각했던 건

  • 한 유저를 여러 번 신고할 수도 있지만, 동일한 유저에 대한 신고 횟수는 1회로 처리됩니다.
  • 자기 자신을 신고하는 경우는 없습니다.

이 두개였다. 

동일한 유저에 대한 신고 횟수 즉, 중복 처리는 'Set'을 간단히 떠올렸다(아는게 Set 밖에 없다.). 그리고 자기 자신을 신고하는 경우는 report 배열 내 값을 for문을 돌 때 'split()' 메서드를 사용해 신고자와 피신고자를 분리 후, 신고자와 피신고자가 같을 경우에는 list에서 해당 요소를 제거하고 countinue 하도록 로직을 정리했다.

 

 

Code1

import java.util.*;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        int[] answer = new int[id_list.length];
        int[] reportAccumulate = new int[id_list.length];
        List<String> idList = Arrays.asList(id_list);
    	
        // 중복 제거
        HashSet<String> set = new HashSet<>(Arrays.asList(report));
        // set -> list
        List<String> list = new ArrayList<>(set);
        
        
        for(int i = 0; i < list.size(); i++) { // 신고 누적 처리
            String[] people = list.get(i).split(" ");
            String reporter = people[0];
            String respondent = people[1];

            if(reporter.equals(respondent)) { // 자기 자신 신고 삭제
                list.remove(list.get(i));
                continue;
            }
            else {
                int respondentIndex = idList.indexOf(respondent);
                reportAccumulate[respondentIndex]++;
            }
        }

        for(int j = 0; j < list.size(); j++) { // 메일 횟수 처리
            String[] people = list.get(j).split(" ");
            String reporter = people[0];
            String respondent = people[1];
            int respondentIndex = idList.indexOf(respondent);
            
            for(int l = 0; l < id_list.length; l++) {
                if(reportAccumulate[l] >= k && l==respondentIndex) {
                    answer[idList.indexOf(reporter)]++;
                    break;
                }
            }
        }
        return answer;
    }
}

 

너무나 충격적인 코드가 나와버렸다. 일단 제일 문제점은 for문들 안에 중복적인 코드가 KTX를 타고 가면서 봐도 많았다. 그래서 대안으로 Map을 생각했는데 Key가 중복이 안 된다는 문제 때문에 List<Map<>>의 형태로 구현하였다.

 

 

Code2

import java.util.*;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        int[] answer = new int[id_list.length];
        int[] reportAccumulate = new int[id_list.length];
        
        HashSet<String> set = new HashSet<>(Arrays.asList(report));
        List<Map<String, String>> list = new ArrayList<>();
        
        for(String s : set) { // set 요소 list에 담기
            String[] reportPerson = s.split(" ");
            String reporter = reportPerson[0];
            String respondent = reportPerson[1];
            
            Map<String, String> map = new HashMap<>();
            if(reporter.equals(respondent)) continue; // 자기 자신 제외
            else map.put(reporter, respondent);
            
            list.add(map);
        }
        
        for (int i = 0; i < list.size(); i++) { // 신고 누적 처리
            String id = (String)list.get(i).keySet().toArray()[0];
            int respondentIndex = Arrays.asList(id_list).indexOf(list.get(i).get(id));
            reportAccumulate[respondentIndex]++;
        }
        
        for (int i = 0; i < list.size(); i++) { // 메일 횟수처리
            String id = (String)list.get(i).keySet().toArray()[0];
            int respondentIndex = Arrays.asList(id_list).indexOf(list.get(i).get(id));
            for (int j = 0; j < id_list.length; j++) {
                if(reportAccumulate[j] >= k && j==respondentIndex) {
                    int reporterIndex = Arrays.asList(id_list).indexOf(id);
                    answer[reporterIndex]++;
                    break;
                }
            }
        }
        return answer;
    }
}

 

조금 더 깔끔해진 것 같기도하고 한눈에 들어오지 않는 것 같기도 하다....!!! 둘 다 돌려보니 속도는 비슷한 것 같다. 어떤 코드가 더 나은지는 모르겠지만 기존 코드를 List<Map<>> 형태로 바꾸면서 Map에 대해 좀 더 공부를 한 것 같다.

반응형
반응형

 

반응형

 

 

결과

Code1, Code2

반응형