如何实现Kotlin数组最大元素索引(空数组返回null)及代码咨询
Fixing the
indexOfMax Function in Kotlin Let's fix your indexOfMax function step by step—there are a few key issues in your current code that are preventing it from working as expected:
- No handling for empty arrays: Your function needs to return
nullif the input array is empty, but your current code doesn't check this at all. - Incorrect loop syntax: The loop should be
for (i in 0..a.lastIndex)(you missedinand thea.prefix forlastIndex). - Wrong initialization for max value: Initializing
maxto 0 will fail if all elements in the array are negative. You should start with the first element of the array as the initial max value. - Swapped assignment in comparison: You have
e = maxwhen you should be updatingmaxtoewhen a larger element is found. - Returning the max value instead of its index: Your function is supposed to return the index of the maximum element, not the element itself.
Here's the corrected version of the function:
fun indexOfMax(a: IntArray): Int? { // Handle empty array case first if (a.isEmpty()) return null var maxIndex = 0 var maxValue = a[0] // Iterate from the second element to the end for (i in 1..a.lastIndex) { val currentValue = a[i] if (currentValue > maxValue) { maxValue = currentValue maxIndex = i } } return maxIndex }
Explanation:
- We first check if the array is empty and return
nullimmediately if it is. - We initialize
maxIndexto 0 (the index of the first element) andmaxValueto the first element's value. - We loop starting from index 1 (since we already considered index 0) and compare each element to the current
maxValue. - Whenever we find a larger element, we update both
maxValueto this new element andmaxIndexto its position. - Finally, we return
maxIndex, which holds the position of the largest element in the array.
If you prefer a more idiomatic Kotlin approach using standard library functions, you could also write it like this:
fun indexOfMax(a: IntArray): Int? { return if (a.isEmpty()) null else a.indices.maxByOrNull { a[it] } }
This uses maxByOrNull on the array's indices, comparing each index by the corresponding element value, which gives us the index of the maximum element directly.
内容的提问来源于stack exchange,提问作者AbdElrahman Usama
相关产品推荐
相关产品推荐

