有谁知道如何从此函数中获取最大元素的索引:
编程语言是scala
def indexOfLargestElement(arr: Array[Int]): Int =
例如:
indexOfLargestElement(Array( 1, -6, 4, 5, 2, -1) ) == 3
我不明白-.-
谢谢你的帮助!
最佳答案
以下是单次遍历的方法:
def indexOfLargest(array: Seq[Int]): Int = {
val result = array.foldLeft(-1,Int.MinValue,0) {
case ((maxIndex, maxValue, currentIndex), currentValue) =>
if(currentValue > maxValue) (currentIndex,currentValue,currentIndex+1)
else (maxIndex,maxValue,currentIndex+1)
}
result._1
}
这将使用一个元组(已知最大元素的索引;最大元素的值;当前索引)来保存循环中的数据。
关于arrays - 数组中最大元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551770/