android - 如果数组为空,如何找到最大的数字和 null

标签 android arrays kotlin

有趣的 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/

相关文章:

android - 获取用于解析嵌套的 Parcelable 泛型字段的泛型类加载器

Android ListView setAdapter问题

android - java.lang.IllegalStateException : Underflow in restore - more restores than saves 错误

c - 为什么这个数组的所有剩余值都初始化为零?

java - Kotlin Jackson Mapper 将 String 反序列化为 HashMap<String, Any> 而不是类型

android - 如何在 Android Kotlin 的 For 循环中获取列表项的索引?

android - 在 fragment 中获取对 LinearLayout 的引用

java - AsyncTask错误Android应用程序崩溃

javascript - 如何使用 javascript 或 Angular 将一个数组的每个元素添加到其他数组中的相应元素

java - 如何从数组中检索数据?