eetcode - reduce array size to the half(kotlin)


level - medium
[質問]
配列内で削除する数値セットを選択し、そのセットの半分以下を削除する最小値を返します.
[example 1]
Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array.
[example 2]
Input: arr = [7,7,7,7,7,7]
Output: 1
Explanation: The only possible set you can choose is {7}. This will make the new array empty.
[example 3]
Input: arr = [1,9]
Output: 1
[example 4]
Input: arr = [1000,1000,3,7]
Output: 1
[example 5]
Input: arr = [1,2,3,4,5,6,7,8,9,10]
Output: 5
[解決策]
与えられた配列の繰返し係数の個数を求めて地図に保存する.
重複する個数を降順に並べ替えます.
与えられた配列から1つまたは複数を降順に削除する場合
減算された数値の個数を返します.
class Solution {
    fun minSetSize(arr: IntArray): Int {
        val counts = HashMap<Int, Int>()
        // 중복된 숫자 count
        for(a in arr) {
            counts[a] = counts.getOrDefault(a, 0) + 1
        }

        // 중복된 개수에 대해 내림차순 정렬
        val keySet = counts.keys.toList()
        Collections.sort(keySet, kotlin.Comparator { t, t2 -> counts[t2]!!.compareTo(counts[t]!!) })
        
        val half = arr.size/2
        var count = 0
        var value = 0
        // 중복 개수의 내림차순으로 숫자 꺼냄
        for(key in keySet) {
            count++
            value += counts[key]!!
            // 꺼낸 개수가 절반보다 크거나 같을경우 break
            if(half <= value) {
                break
            }
        }

        return count
    }
}