数组中最大元素的索引

时间:2013-03-21 15:33:11

标签: arrays scala for-loop

有谁知道如何从这个函数中获取最大元素的索引:

编程语言是scala

def indexOfLargestElement(arr: Array[Int]): Int = 

例如:

indexOfLargestElement(Array( 1, -6, 4, 5, 2, -1) ) == 3

我不明白 - .-

感谢您的帮助!

6 个答案:

答案 0 :(得分:10)

以下是使用单次遍历的方法:

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
}

这将使用元组(已知最大元素的索引;最大元素的值; curent索引)来保存循环中的数据。

答案 1 :(得分:6)

// val l = Array(1, -6, 4, 5, 2, -1)
l.indexOf(l.max)

答案 2 :(得分:5)

scala> :paste
// Entering paste mode (ctrl-D to finish)

@annotation.tailrec final def indexOfLargestElement(a: Array[Int], i: Int = -1, mi: Int = -1, ma: Int = Int.MinValue): Int = {
  val i1 = i + 1
  if (i1 < a.length) {
    val ai1 = a(i1)
    if (ai1 >= ma) indexOfLargestElement(a, i1, i1, ai1)
    else indexOfLargestElement(a, i1, mi, ma)
  } else mi
}

// Exiting paste mode, now interpreting.

indexOfLargestElement: (a: Array[Int], i: Int, mi: Int, ma: Int)Int

scala> indexOfLargestElement(Array(1, -6, 4, 5, 2, -1))
res0: Int = 3

scala> indexOfLargestElement(Array())
res1: Int = -1

scala> indexOfLargestElement(Array(Int.MinValue))
res2: Int = 0

答案 3 :(得分:4)

我不确定性能是什么,因为可能存在昂贵的隐式转换,我无法确定哪种排序算法是实际使用的。

仍然是这个

scala> val arr = Array( 1, -6, 4, 5, 2, -1)
arr: Array[Int] = Array(1, -6, 4, 5, 2, -1)

scala> arr.zipWithIndex.maxBy(_._1)._2
res1: Int = 3

答案 4 :(得分:0)

我的解决方案非常基础,但很容易理解

/** 
 * Returns the max index or -1 if there is no max index
 */
def getMaxIndex(array: Array[Int]): Int = {
  var maxIndex = -1
  var max = Int.MinValue
  for {
    index <- 0 until array.length
    element <- array
  } {
    if (element > max) {
      max = element
      maxIndex = index
    }
  }
  maxIndex
}

基本相同
/** 
 * Returns the max index or -1 if there is no max index
 */
def getMaxIndex(array: Seq[Int]): Int = {
    val startIndex = 0
    val result = array.foldLeft(-1, Int.MinValue, startIndex) {
        case ((maxIndex, max, index), element) => {
            if(element > max) (index, element, index+1)
            else (maxIndex, max, index+1)
        }
    }
    result._1
}

答案 5 :(得分:0)

相同的解决方案以及上面的一些解决方案,但是尾递归更多:

  def getMaxIndex(a: Array[Double]): Int = {
    val l = a.length

    def findMax(v: Double, k: Int, i: Int): Int = {
      if (i < l) {
        if (v < a(i)) findMax(a(i), i, i + 1) else findMax(v, k, i + 1)
      } else k
    }

    findMax(Double.NegativeInfinity, -1, 0)
  }

真正的尾递归使该过程更易于理解。调用矩阵本身也很容易,它本身不会修改矩阵,反而使它变得更快。每个元素只访问一次。

基本上是Alex Yarmula和Andriy Plokhotnyuk解决方案的简单版本。