首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >查找数组的最小和最大元素

查找数组的最小和最大元素
EN

Stack Overflow用户
提问于 2013-11-29 19:52:54
回答 8查看 65.1K关注 0票数 27

我想要找到一个数组的最小和最大元素,用于理解。有没有可能用一次数组迭代来同时找到最小元素和最大元素?

我正在寻找一个不使用scala提供的array.min或max的解决方案。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2013-11-29 20:15:11

下面是一个简洁易读的解决方案,它避免了丑陋的if语句:

代码语言:javascript
复制
def minMax(a: Array[Int]) : (Int, Int) = {
  if (a.isEmpty) throw new java.lang.UnsupportedOperationException("array is empty")
  a.foldLeft((a(0), a(0)))
  { case ((min, max), e) => (math.min(min, e), math.max(max, e))}
}

说明:foldLeft是Scala中许多集合的标准方法。它允许将累加器传递给回调函数,该回调函数将为数组的每个元素调用。

有关更多详细信息,请查看scaladoc

票数 29
EN

Stack Overflow用户

发布于 2013-11-29 20:14:16

代码语言:javascript
复制
def findMinAndMax(array: Array[Int]) = { // a non-empty array

    val initial = (array.head, array.head)  // a tuple representing min-max


    // foldLeft takes an initial value of type of result, in this case a tuple
    // foldLeft also takes a function of 2 parameters.
    // the 'left' parameter is an accumulator (foldLeft -> accum is left)
    // the other parameter is a value from the collection.

    // the function2 should return a value which replaces accumulator (in next iteration)
    // when the next value from collection will be picked.

    // so on till all values are iterated, in the end accum is returned.

    array.foldLeft(initial) { ((min, max), x) => 
          if (x < min) (x, max) 
          else if (x > max) (min, x) 
          else acc 
    }
}
票数 6
EN

Stack Overflow用户

发布于 2015-05-09 00:22:56

从其他答案继续-更通用的解决方案是可能的,它适用于其他集合以及Array和其他内容以及Int

代码语言:javascript
复制
def minmax[B >: A, A](xs: Iterable[A])(implicit cmp: Ordering[B]): (A, A) = {
  if (xs.isEmpty) throw new UnsupportedOperationException("empty.minmax")

  val initial = (xs.head, xs.head)

  xs.foldLeft(initial) { case ((min, max), x) => 
    (if (cmp.lt(x, min)) x else min, if (cmp.gt(x, max)) x else max) }
}                                               

例如:

代码语言:javascript
复制
minmax(List(4, 3, 1, 2, 5))              //> res0: (Int, Int) = (1,5)

minmax(Vector('Z', 'K', 'B', 'A'))       //> res1: (Char, Char) = (A,Z)

minmax(Array(3.0, 2.0, 1.0))             //> res2: (Double, Double) = (1.0,3.0)

(也可以使用cmp.min()cmp.max()更简洁地编写此代码,但前提是删除了B >: A类型绑定,这会使函数不那么通用)。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20285209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档