Developing Myself Everyday
article thumbnail

문제 출처: https://school.programmers.co.kr/learn/courses/30/lessons/92341?language=kotlin

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제

나의 풀이 - 1차

tangerine에 있는 값을 숫자와 빈도수로 나눠서 map에 넣었다. 그리고 map을 value 값으로 정렬 후 k값이 0보다 작아질 때 까지 count하고 그 count 값을 출력해줬다. 테스트 케이스에서는 작동했지만 제출 후 채점에서 오류가 발생했다.

class Solution {
    fun solution(k: Int, tangerine: IntArray): Int {
        var kk: Int = k
        var count = 0
        var map = mutableMapOf<Int, Int>()
        tangerine.map {
            map[it] = map.getOrDefault(map[it]?: 0, 0) + 1
        }
        map.toList().sortedByDescending { it.second }.toMap().map{
            if(kk > 0) {
                kk -= it.value
                count++
            }
        }
        return count
    }
}

나의 풀이 - 2차

map에 넣어줄때 map.getOrDefault(map[it]?: 0, 0)을 썼었는데 변수선언을 따로 해주고 map에 넣으니까 오류가 나지 않았다. 이유를 모르겠어서 알아봐야한다.

class Solution {
    fun solution(k: Int, tangerine: IntArray): Int {
        var kk: Int = k
        var count = 0
        var map = mutableMapOf<Int, Int>()
        tangerine.map {
            val cnt = map[it]?:0
            map[it] = cnt + 1
        }
        map.toList().sortedByDescending { it.second }.toMap().map{
            if(kk > 0) {
                kk -= it.value
                count++
            }
        }
        return count
    }
}

 

'프로그래머스 - kotlin > LEVEL 2' 카테고리의 다른 글

타겟 넘버  (0) 2022.12.08
괄호 변환  (0) 2022.12.03
소수 찾기  (0) 2022.11.29
가장 큰 수  (0) 2022.11.29
모음 사전  (0) 2022.11.25
profile

Developing Myself Everyday

@배준형

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!