有趣的 indexOfMax(a: IntArray): Int? { 返回 0
任务链接 https://try.kotlinlang.org/#/Examples/Problems/Index%20of%20Maximum/Index%20of%20Maximum.kt
我的尝试:
fun indexOfMax(a: IntArray): Int? {
var max = 0
for (i 0..lastIndex){
e = a[i]
if (e > max){
e = max
}
}
return max
}
最佳答案
在 Kotlin 中,您只需一行代码即可完成。
如果您正在寻找最大元素或如果数组为空则为 null:
return array.max()
如果您要查找最大元素的索引,如果数组为空则为 null:
return array.max()?.let { array.indexOf(it) }
在给定的问题中,您需要查找最后一个索引:
return array.max()?.let { array.lastIndexOf(it) }
函数源代码:
/**
* Returns the largest element or `null` if there are no elements.
*/
public fun IntArray.max(): Int? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
和
/**
* Returns first index of [element], or -1 if the array does not contain element.
*/
public fun IntArray.indexOf(element: Int): Int {
for (index in indices) {
if (element == this[index]) {
return index
}
}
return -1
}
关于android - 如果数组为空,如何找到最大的数字和 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49966567/