阅读 45

LeetCode之Group the People Given the Group Size They Belong To(Kotlin)

问题:


方法: 通过map结构存储list,当list装满groupSize时移到result中即可,遍历所有元素即可得到最终结果。

class GroupThePeopleGivenTheGroupSizeTheyBelongTo {
    fun groupThePeople(groupSizes: IntArray): List<List<Int>> {
        val result = mutableListOf<List<Int>>()
        val map = mutableMapOf<Int, MutableList<Int>>()
        for (el in groupSizes.withIndex()) {
            val index = el.index
            val groupSize = el.value
            val list = map.getOrDefault(groupSize, mutableListOf())
            list.add(index)
            if (list.size == groupSize) {
                result.add(list)
                map.remove(groupSize)
            } else {
                map[groupSize] = list
            }
        }
        return result
    }
}

fun main(args: Array<String>) {
    val groupSizes = intArrayOf(3, 3, 3, 3, 3, 1, 3)
    val groupThePeopleGivenTheGroupSizeTheyBelongTo = GroupThePeopleGivenTheGroupSizeTheyBelongTo()
    val result = groupThePeopleGivenTheGroupSizeTheyBelongTo.groupThePeople(groupSizes)
    println(result)
}
复制代码

有问题随时沟通

具体代码实现可以参考Github