LeetCode之Group the People Given

2019-12-27  本文已影响0人  糕冷羊

问题:



方法:
通过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

上一篇下一篇

猜你喜欢

热点阅读