문제 풀이/기타

[백준] 10816 (숫자 카드 2)

interfacer_han 2024. 2. 6. 11:26

#1 코드 - 코틀린

import java.lang.StringBuilder

fun main() {
    // Initiation
    val n = readln().toInt()
    val cardNumberInputs = readln().split(" ")

    val cardNumbers = Array(n) {0}
    for(i: Int in 0..<n) {
        cardNumbers[i] = cardNumberInputs[i].toInt()
    }

    val m = readln().toInt()
    val targetCardNumberInputs = readln().split(" ")

    val targetCardNumbers = Array(m) {0}
    for(i: Int in 0..<m) {
        targetCardNumbers[i] = targetCardNumberInputs[i].toInt()
    }

    // Make Map
    val cardCountMap = HashMap<Int, Int>()
    for(cardNumber in cardNumbers) {
        if(cardCountMap[cardNumber] == null) {
            cardCountMap[cardNumber] = 1
        } else {
            cardCountMap[cardNumber] = cardCountMap[cardNumber]!! + 1
        }
    }

    // Make output
    val output = StringBuilder()
    for(i: Int in 0..<m) {
        if(cardCountMap[targetCardNumbers[i]] == null) {
            output.append("0 ")
        } else {
            output.append("${cardCountMap[targetCardNumbers[i]]} ")
        }
    }
    println(output)
}

Map<Int, Int>형 변수 cardCountMap을 선언하고, 어떤 수(Int)가 몇 개(Int) 들어가는지를 해당 Map에 저장해나간다.

'문제 풀이 > 기타' 카테고리의 다른 글

[백준] 21736 (헌내기는 친구가 필요해)  (0) 2024.03.02
[백준] 1074 (Z)  (0) 2024.03.01
[백준] 1929 (소수 구하기)  (0) 2024.02.05
[백준] 18110 (solved.ac)  (0) 2024.01.08
[백준] 17626 (Four Squares)  (0) 2024.01.03