在Kotlin数组中的indexOf

tal*_*ees 16 arrays kotlin

如何从Kotlin数组中获取值的索引?

我现在最好的解决方案是使用:

val max = nums.max()
val maxIdx = nums.indices.find({ (i) -> nums[i] == max }) ?: -1
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

小智 16

如果要获取最大元素的索引,可以使用'maxBy'函数:

val maxIdx = nums.indices.maxBy { nums[it] } ?: -1
Run Code Online (Sandbox Code Playgroud)

它更有效,因为它只遍历数组一次.

  • @Jayson,你对新的`indexOf()`函数的回答并没有以任何方式过时这个答案,因为它仍然擅长单遍历. (3认同)

Jay*_*ard 9

使用当前的Kotlin(1.0),您可以在数组上使用indexOf()扩展功能:

val x = arrayOf("happy","dancer","jumper").indexOf("dancer")
Run Code Online (Sandbox Code Playgroud)

数组的所有扩展函数都可以在api参考中找到.

在你的例子中:

val maxIdx = nums.indexOf(nums.max())
Run Code Online (Sandbox Code Playgroud)