美文网首页
LeetCode之Group the People Given

LeetCode之Group the People Given

作者: 糕冷羊 | 来源:发表于2019-12-27 15:47 被阅读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

    相关文章

      网友评论

          本文标题:LeetCode之Group the People Given

          本文链接:https://www.haomeiwen.com/subject/svedoctx.html