Lv1. 신고 결과 받기

Hello·2022년 7월 31일

코딩테스트 연습 > 신고 결과 받기

1. 풀이 설명

  1. HashMap<String, MytableSet<String>> map 을 정의한다. key는 신고 받은 유저, value는 key를 신고한 유저 리스트를 중복없이 저장한다.

  2. report"from to" 아이템들을 map 에 저장한다.

  3. id_list 를 for문 돌면서, id가 key를 신고를 한 유저이면서 key를 신고한 전체 유저의 수가 k 이상인 key의 개수를 answer 에 추가한다.

2. 나의 풀이

python

def solution(id_list, report, k):
    answer = [0] * len(id_list)
    dic = {x: [] for x in id_list}

	# a가 b 를 신고했다.
    for r in set(report):
        a = r.split()[0]
        b = r.split()[1]
        dic[b].append(a)

    for d in dic:
        if len(dic[d]) >= k:
            for a in dic[d]:
                answer[id_list.index(a)] += 1

    return answer

kotlin

fun solution(id_list: Array<String>, report: Array<String>, k: Int): IntArray {
    val answer = arrayListOf<Int>()
    val map: HashMap<String, MutableSet<String>> = hashMapOf()
        
    report.map {
        it.split(" ")
    }.forEach { item ->
        val from = item[0]
        val to = item[1]
        if (map.contains(to)) {
            map[to]?.add(from)
        } else {
            map[to] = mutableSetOf(from)
        }
    }

    id_list.forEach { id ->
        answer.add(
            map.filter {
                it.value.contains(id) && it.value.size >= k
            }.count()
        )
    }
    return answer.toIntArray()
}

3. 배운점

  • 신고한 유저, [신고 받은 유저]

python

  1. list 에서 아이템의 index: list.index(item)

kotlin

  1. flatten()
    : 중첩 Collection을 펼쳐서 하나의 Collection 으로 만든다.
val list = listOf(
 	listOf(1),
    listOf(2, 3),
    listOf(1, 2, 3)
)

println(list.flatten())		// [1, 2, 3, 1, 2, 3]
println(list.flatten().distinct())	// [1, 2, 3]
profile
안녕하세요 :)

0개의 댓글