我给出了一个整数列表。我需要始终映射以下两个元素以进一步推进。如果输入列表包含无效的元素计数,则应删除最后的元素。下面是一个例子:
[1, 2, 3, 4, 5, 6, 7] //Input
[(1, 2), (3, 4), (5, 6)] //Output
Run Code Online (Sandbox Code Playgroud)
我写信给函数以获得想要的输出,但我认为它们都是低效的。
首先,我用函数式方法尝试了它。但是它需要两个过滤器调用和一个对结果列表的 zip 调用。所以它在entier列表上迭代2.5次。
Two imrpove this I tried a iterative approach. It only iterates once over the list and is possibly the fastest version. But it uses multiple mutable variables/lists. Also it is not as easy to understand as the functinal approach. (And it breaks the cleaness of the rest of the code)
fun main(args: Array<String>) {
mapFunctional()
mapIterative()
}
fun mapFunctional() { …
Run Code Online (Sandbox Code Playgroud) kotlin ×1