[프로그래머스] 신고 결과 받기 in Kotlin

ddanglehee·2022년 8월 3일
0

코딩테스트 준비

목록 보기
1/18
post-thumbnail

📜 문제

문제 링크

💡 나의 풀이

1. reportMap 초기화
    유저ID로 해당 유저의 신고 정보(유저가 신고 당한 횟수와 신고한 유저ID 리스트)에 O(1)만에 접근할 수 있도록, 유저ID를 key로 가지고 유저의 신고 정보(Report 클래스)를 value로 가지는 HashMap으로 구현했다.
2. 신고 내역 반영하기
    문제에 "한 유저를 여러 번 신고할 수도 있지만, 동일한 유저에 대한 신고 횟수는 1회로 처리됩니다." 라는 조건이 있기 때문에 먼저 신고자의 reportIdSet에 해당 피신고자가 있는지 확인한 후, 없는 경우에만 신고 내역을 반영(신고자의 reportIdSet에 피신고자를 추가하고, 피신고자의 reportedCount를 1 증가시킴)한다.
3. 신고 결과 처리하기
    유저ID를 순회하면서 유저가 신고한 유저들이 k번 이상 신고를 당했는지 검사한다. k번 이상 신고됐다면 신고 결과 메일을 받는 것이므로 answer + 1

⌨️ 코드

class Solution {
    fun solution(id_list: Array<String>, reports: Array<String>, k: Int): IntArray {
        val answer = IntArray(id_list.size) { 0 }

		// 1. reportMap 초기화
        val reportMap = hashMapOf<String, Report>()
        id_list.forEachIndexed { index, id ->
            reportMap[id] = Report(index)
        }

		// 2. 신고 내역 반영하기
        reports.forEach { report ->
            val (reporter, respondent) = report.split(" ")

            if (respondent !in reportMap[reporter]!!.reportIdSet) {
                reportMap[reporter]!!.reportIdSet.add(respondent)
                reportMap[respondent]!!.reportedCount++
            }
        }

		// 3. 신고 결과 처리하기
        id_list.forEach { id ->
            reportMap[id]!!.reportIdSet.forEach { reportedId ->
                if (k <= reportMap[reportedId]!!.reportedCount) {
                    answer[reportMap[id]!!.index]++
                }
            }
        }
        return answer
    }
    
    inner class Report(val index: Int) {
        val reportIdSet = mutableSetOf<String>()
        var reportedCount = 0
    }
}

😄 느낀 점

"한 유저를 여러 번 신고할 수도 있지만, 동일한 유저에 대한 신고 횟수는 1회로 처리됩니다." 라는 조건을 reports를 set에 담아서 처리했어도 좋았을 거 같다.
또한 3. 신고 결과 처리하기에서 2중 for문이 돌고있는 게 영 찜찜하다. 빠른 시일 내로 수정해봐야겠다.

profile
잊고싶지 않은 것들을 기록해요✏️

0개의 댓글