반응형
```
백준 11652번 카드 Kotlin 구현해 보기
```
이번 글을 통해 배워갈 내용
- 백준 11652번 카드 풀이
https://www.acmicpc.net/problem/11652
11652번: 카드
준규는 숫자 카드 N장을 가지고 있다. 숫자 카드에는 정수가 하나 적혀있는데, 적혀있는 수는 -262보다 크거나 같고, 262보다 작거나 같다. 준규가 가지고 있는 카드가 주어졌을 때, 가장 많이 가지
www.acmicpc.net
백준 11652번 카드는
N개의 숫자들이 주어지면 최빈도의 숫자를 구해주면 됩니다.
최빈도의 수가 여러 개라면 가장 작은 수를 출력합니다
30분 정도 위에 링크를 방문하셔서 풀어보시고
안 풀리시는 경우에만 아래 해답을 봐주시면 감사하겠습니다.
맵을 사용 해서 빈도수를 구한 다음
가장 빈도수가 높은 수를 구했습니다.
fun main() {
val inputDto = getInput()
print(solution(inputDto))
}
fun getInput(): InputDto {
val numCnt = readln().toLong()
val nums = emptyList<Long>().toMutableList()
for (i in 1..numCnt) {
nums.add(readln().toLong())
}
return InputDto(nums)
}
data class InputDto(
val nums: List<Long>
)
fun findMostFrequentNumber(nums: List<Long>): Long {
val map = emptyMap<Long, Int>().toMutableMap()
nums.forEach { n ->
run {
if (map[n] == null) {
map[n] = 1
} else {
map[n] = map[n]!! + 1
}
}
}
return map.maxWith(compareBy<Map.Entry<Long, Int>> { it.value }.thenByDescending { it.key }).key
}
fun solution(dto: InputDto): String {
return findMostFrequentNumber(dto.nums).toString()
}
// https://codemasterkimc.tistory.com/
테스트
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class MainKtTest {
@Test
fun test() {
assertEquals(
"1",
solution(
InputDto(listOf(5, 1, 2, 1, 2, 1))
)
)
assertEquals(
"7",
solution(
InputDto(listOf(5, 1, 2, 1, 2, 1, 7, 7, 7, 7, 7, 7, 7))
)
)
assertEquals(
"1",
solution(
InputDto(listOf(1, 1, 2, 2, 3, 3))
)
)
assertEquals(
"1",
solution(
InputDto(listOf(2, 2, 1, 1, 3, 3))
)
)
}
}
읽어주셔서 감사합니다
무엇인가 얻어가셨기를 바라며
오늘도 즐거운 코딩 하시길 바랍니다 ~ :)
728x90
반응형
'Kotlin > Kotlin 알고리즘' 카테고리의 다른 글
백준 7795번 먹을 것인가 먹힐 것인가 Kotlin 구현해보기 (0) | 2023.03.11 |
---|---|
백준 20291번 파일정리 Kotlin 구현해보기 (0) | 2023.03.11 |
백준 1015번 수열 정렬 Kotlin 구현해보기 (0) | 2023.03.11 |
백준 1182번 부분수열의 합 Kotlin 구현해보기 (0) | 2023.03.11 |
백준 9663번 N-Queen Kotlin 구현해보기 (0) | 2023.03.10 |