Kotlin 列表中的连续整数组

Par*_*dya 2 integer list kotlin

我有一个按顺序排列的整数列表。我想要的是从列表中获取连续整数组。

例如:

输入:[19, 20, 21, 22, 23, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 59, 60, 61, 62 , 63, 64, 65, 66, 73, 74, 75, 76, 77]

所需输出:[[19, 20, 21, 22, 23], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], [59 , 60, 61, 62, 63, 64, 65, 66], [73, 74, 75, 76, 77]]

这是我的代码:

    private fun getConsecutiveNumbers(srcList: ArrayList<Int>): List<List<Int>> {

        val listConsecNums = ArrayList<List<Int>>()
        var subList = ArrayList<Int>()

        for (i in 0 until srcList.size) {
            subList.add(srcList[i])

            if ((i + 1 >= srcList.size) || (srcList[i] + 1 != srcList[i + 1])) {
                listConsecNums.add(subList)
                subList = ArrayList()
            }
        }

        return listConsecNums

    }


Run Code Online (Sandbox Code Playgroud)

这里,代码假设数字是连续的,并将它们收集在一个列表中,直到找到不连续的数字。

这段代码适用于我想要的一般情况,但我只是想知道是否有更有效的 Kolin-y 方法可以做到这一点。

任何建议将不胜感激。

IR4*_*R42 9

fold与可变列表。如果元素连续,则将其添加到最后一个数组,否则用该元素创建一个新数组

fun getConsecutiveNumbers(srcList: List<Int>): List<List<Int>> {
    return srcList.fold(mutableListOf<MutableList<Int>>()) { acc, i ->
        if (acc.isEmpty() || acc.last().last() != i - 1) {
            acc.add(mutableListOf(i))
        } else acc.last().add(i)
        acc
    }
}
Run Code Online (Sandbox Code Playgroud)