신고 결과 받기 (자바) v2

김재현·2024년 5월 18일
0

알고리즘 풀이

목록 보기
86/89
post-thumbnail

이전 풀이: 신고 결과 받기 (자바)

문제

정답 풀이

import java.util.*;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        
        int[] answer = new int[id_list.length];

        // 각 유저가 신고한 id를 저장. 이 때 중복 제거를 위해 Set 사용
        Map<String, Set<String>> id_report = new HashMap<>();
        for(String id : id_list) {
            id_report.put(id,new HashSet<>());
        }
        for(String repo : report) {
            String[] str = repo.split(" ");
            id_report.get(str[0]).add(str[1]);
        }
        
        // 저장된 id들을 카운트
        Map<String, Integer> reportedNum = new HashMap<>();
        for(Set<String> set : id_report.values()) {
            for(String s : set) {
                reportedNum.put(s,reportedNum.getOrDefault(s,0)+1);
            }
        }
        
        // id_report를 조회하며, 저장된 id의 카운트가 k 이상이라면 answer++ 
        for(int i=0;i<id_list.length;i++) {
            for(String s : id_report.get(id_list[i])) {
                if(reportedNum.get(s) >= k) {
                    answer[i]++;
                }
            }
        }
        
        return answer;
    }
}

주석에 풀이를 써두었다.

풀고 보니 로직 자체는 이전과 비슷했다.

차이점은 Set 자료 구조를 사용했다는 것, 그리고 getOrDefault를 적극 활용했다는 것이다.

또한 저장된 id들을 카운트 할 때 향상된 반복문에 id_report.values()를 사용했다.
이것은 Map 자료구조인 id_report의 모든 value를 조회하는 것이다.

(Set 자료구조의 경우에는 .values() 없이, set 자체를 순회하면 된다.)

profile
I live in Seoul, Korea, Handsome

0개의 댓글