학습/프로그래머스

[프로그래머스] 신고 결과 받기(java)

태기 2023. 2. 2. 18:43

문제

https://school.programmers.co.kr/learn/courses/30/lessons/92334

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


나의 풀이

import java.util.ArrayList;
import java.util.HashMap;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        int idLen = id_list.length;
        int[] answer = new int[idLen];
        HashMap<String, ArrayList<String>> reportMap = new HashMap<>();
        HashMap<String, Integer> indexMap = new HashMap<>();

        for (int i = 0; i < idLen; i++) {
            reportMap.put(id_list[i], new ArrayList<>());
            indexMap.put(id_list[i], i);
        }

        for (String repo : report) {
            String[] re = repo.split(" ");
            ArrayList<String> arrayReport = reportMap.get(re[1]);

            if (arrayReport.indexOf(re[0]) == -1) {
                arrayReport.add(re[0]);
            }
            reportMap.put(re[1], arrayReport);
        }

        for (String id : id_list) {
            ArrayList<String> arrayList = reportMap.get(id);
            if (arrayList.size() >= k) {
                for (String name : arrayList) {
                    answer[indexMap.get(name)]++;
                }

            }
        }

        return answer;
    }
}

어떤 유저가 누구를 신고했는지 저장하는 reportMap 객체와 유저의 신고 횟수를 저장하는 indexMap을 초기화하는 첫 번째 반복문은 id_list의 길이에 따라 횟수가 변하므로 O(n)이며 증가 차수는 선형이다.

 

두 번째 반복문은 report의 길이만큼 순회하여 O(n)이고 증가 차수는 선형이다. 중간에 조건문은 유저가 신고한 대상이 중복되는지 확인하고 없으면 추가하는 코드이다. 이걸 Set 객체를 쓰면 되는데, 이 문제를 풀 때는 왜 그 생각을 못했을까; 아무튼 Set을 쓰면 중복 체크할 일이 없이 사용 가능하다.

 

마지막 반복문은 다시 유저를 보며 신고한 유저가 신고를 k번 이상 했는지 확인하여 메일 받는 횟수를 입력한다. 마찬가지로 O(n)이며 선형이다.