gpt4 book ai didi

kotlin - 如何有效地从Kotlin的集合(前N个)中获取N个最低值?

转载 作者:行者123 更新时间:2023-12-02 13:01:51 24 4
gpt4 key购买 nike

如何有效地从Kotlin的集合(前N个)中获取N个最低值?

除了collectionOrSequence.sortedby{it.value}.take(n)还有其他方法吗?

假设我有一个包含+100500元素的集合,我需要找到10个最低的元素。恐怕sortedby会创建新的临时集合,以后只需要10个项目。

最佳答案

您可以保留n个最小元素的列表,然后按需更新它,例如

fun <T : Comparable<T>> top(n: Int, collection: Iterable<T>): List<T> {
return collection.fold(ArrayList<T>()) { topList, candidate ->
if (topList.size < n || candidate < topList.last()) {
// ideally insert at the right place
topList.add(candidate)
topList.sort()
// trim to size
if (topList.size > n)
topList.removeAt(n)
}
topList
}
}

这样,您只需将列表中的当前元素与前n个元素中的最大元素进行一次比较,通常比对整个列表进行排序 https://pl.kotl.in/SyQPtDTcQ

关于kotlin - 如何有效地从Kotlin的集合(前N个)中获取N个最低值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52770018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com