[알고리즘 문제풀이] 프로그래머스 - 신고 결과 받기

yourjin·2022년 3월 11일
0

알고리즘 문제풀이

목록 보기
20/28
post-thumbnail

TIL (2022.03.11)

➕ 오늘 푼 문제


프로그래머스 - 신고 결과 받기

➕ 아이디어


  • report에서 중복을 제거한다.
  • 아이디별 신고 받은 횟수를 담는 해시(report_count)를 만든다
    • key: 아이디 / value : 신고 받은 횟수
  • report 를 반복하며, 유저가 신고한 ID가 신고 받은 횟수k 번 이상이면 유저ID는 메일을 받는다. 따라서 유저ID의 answer값을 1 증가시킨다.
    • 유저가 신고한 ID가 신고 받은 횟수 = key가 유저가 신고한 ID인 report_count 의 value

➕ Java 코드


import java.util.*;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        int[] answer = new int[id_list.length];
        HashMap<String, Integer> report_count = new HashMap<String, Integer>();
        HashSet<String> report_set = new HashSet<String>(Arrays.asList(report));
        
        for(String r: report_set){
            String key = r.split(" ")[1];
            report_count.put(key, report_count.getOrDefault(key, 0) + 1);
        }
        
        for(String r: report_set){
            String[] id = r.split(" ");
            if(report_count.get(id[1]) >= k){
                int index = Arrays.asList(id_list).indexOf(id[0]);
                answer[index] += 1;
            }
        }
        return answer;
    }
}

➕ Python 코드


def solution(id_list, report, k):
    answer = [0] * len(id_list) 
    report_count = {i : 0 for i in id_list}
    
    for r in set(report):
        from_id, to_id = r.split()
        report_count[to_id] += 1
    
    for r in set(report):
        from_id, to_id = r.split()
        if report_count[to_id] >= k:
            index = id_list.index(from_id)
            answer[index] += 1
            
    return answer

➕ 궁금한 내용 및 소감


  • 해결 아이디어를 내는 것은 어렵지 않았지만, 깔끔하게 구현하는 것이 조금 어려웠던 문제였다. 파이썬, 자바 둘 다 내장 함수를 잘 활용하면 더욱 깔끔하게 풀 수 있었다.
    • 파이썬의 경우 dictionary comprehension이나, index() 가 특히 유용했다.
    • 자바의 경우 향상된 for문, Arrays.asList(), indexOf() 가 유용했다.

➕ 참고 문헌


profile
make it mine, make it yours

0개의 댓글