본문 바로가기
알고리즘/프로그래머스

[2023-06-17] [프로그래머스 lv1] 신고 결과 받기 (Kotlin)

by joh9911 2023. 6. 17.

 

와 lv2 보다 더 오래걸렸습니다.

 

저만 그런건지 모르겠는데, 더 어려웠던 것 같아요.

 

1시간 걸렸습니다.

 

 

package seventyFourth

class `lv1 신고 결과 받기` {
    class Solution {
        fun solution(id_list: Array<String>, report: Array<String>, k: Int): IntArray {
        
        	// 각 id 별 신고한 id를 저장하는 2차원 배열
            val reporterArr = Array(id_list.size){mutableSetOf<String>()}
            
            // 각 id 별 배열의 위치를 저장
            val idLocationMap = mutableMapOf<String,Int>()
            for (index in id_list.indices){
                idLocationMap[id_list[index]] = index
            }
			
            // id 별 신고 당한 수롤 저장하는 map
            val countMap = mutableMapOf<String,Int>()
			
            // 신고 당한 수와, 각 id 별 신고한 id들을 저장하는 반복문
            for (index in report.indices){
                val split = report[index].split(' ')
                val reporter = split.first()
                val reported = split.last()
                val reporterIdx = idLocationMap[reporter]!!
				
                // id가 처음으로 신고를 할 때만 count 저장
                if (reported !in reporterArr[reporterIdx])
                    countMap[reported] = countMap.getOrDefault(reported, 0) + 1

                reporterArr[reporterIdx].add(reported)
            }

            var answer: IntArray = IntArray(id_list.size)
            val reportedList = countMap.filterValues{it >= k}.keys
			
            // 각 id가 신고한 사람들 중, reportedList에 포함될 경우 1을 더해줌
            for (i in reporterArr.indices){
                var resultCount = 0
                reporterArr[i].forEach{
                    if (it in reportedList)
                        resultCount += 1
                }
                answer[i] = resultCount
            }

            return answer
        }
    }
}

댓글