kotlin - 查找数组的第二/第三/第四最小值
问题描述
我想在数组中找到第二个最小值并返回它,以及第三个、第四个等。我设法通过此处发布的解决方案找到了最小值,但我找不到正确的语法来获取接下来是第二个最低值,可能是通过从变量中删除最低值。到目前为止,我是这样做的:
val (minValue, minInt) = Values.zip(Ints).minBy { (_ /* Value not needed */, rating) ->
rating } ?: throw IllegalArgumentException("Cannot find the minimum of an empty list.")
解决方案
在数组上调用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]
推荐阅读
- trello - Trello 开机显示多个卡片徽章
- java - 将 vensim 集成到 anylogic 中但出现运算符错误
- node.js - 更改 package.json 时“npm install”和“npm update”的行为是什么?
- oracle - oracle 表单获取表和多行块中的数据
- php - 为什么我的 PHP 会话变量只能在特定浏览器中工作而在其他浏览器中失败?
- php - 在 Symfony 4.2 中通过 Linkedin 登录
- sql - 查询以返回连续 X 天内值的最低 SUM
- python - 在 Jupiter Notebook 中工作的脚本在 IDE 中无法按预期工作
- android - 在“src”中选择资源时,drawable 中的图像不会显示在“资源”部分
- pycharm - pycharm 不会警告未使用的变量和导入