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

问题:



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

class GroupThePeopleGivenTheGroupSizeTheyBelongTo {
    fun groupThePeople(groupSizes: IntArray): List> {
        val result = mutableListOf>()
        val map = mutableMapOf>()
        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) {
    val groupSizes = intArrayOf(3, 3, 3, 3, 3, 1, 3)
    val groupThePeopleGivenTheGroupSizeTheyBelongTo = GroupThePeopleGivenTheGroupSizeTheyBelongTo()
    val result = groupThePeopleGivenTheGroupSizeTheyBelongTo.groupThePeople(groupSizes)
    println(result)
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Group the People Given the Group Size They Belong To(Kotlin))