首页 > 解决方案 > 查找数组的第二/第三/第四最小值

问题描述

我想在数组中找到第二个最小值并返回它,以及第三个、第四个等。我设法通过此处发布的解决方案找到了最小值,但我找不到正确的语法来获取接下来是第二个最低值,可能是通过从变量中删除最低值。到目前为止,我是这样做的:

val (minValue, minInt) = Values.zip(Ints).minBy { (_ /* Value not needed */, rating) ->
        rating } ?: throw IllegalArgumentException("Cannot find the minimum of an empty list.")

标签: kotlin

解决方案


在数组上调用sorted()函数和subList(fromIndex: Int, toIndex: Int)

  • sorted()函数按升序对数组进行排序

  • subList(fromIndex: Int, toIndex: Int)函数根据您提供的 fromIndex 和 toIndex 值返回您需要的数组的一部分。

您可以使用下面的代码进行测试。

val list = arrayOf(1,5,6,4,2,6,7,8)
println(list.sorted().subList(1, 4))

Output : [2, 4, 5]

推荐阅读