查找数组的最小和最大元素 [英] Find min and max elements of array
问题描述
我想找到用于理解的数组的最小和最大元素.是否可以通过一次数组迭代来找到最小元素和最大元素?
I want to find the min and max elements of an array using for comprehension. Is it possible to do that with one iteration of array to find both min element and max element?
我正在寻找不使用 Scala 提供的 array.min 或 max 的解决方案.
I am looking for a solution without using scala provided array.min or max.
推荐答案
这是一个简洁易读的解决方案,它避免了丑陋的 if
语句:
Here is a concise and readable solution, that avoids the ugly if
statements :
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 中许多集合的标准方法.它允许将累加器传递给回调函数,该函数将为数组的每个元素调用.
Explanation : foldLeft
is a standard method in Scala on many collections. It allows to pass an accumulator to a callback function that will be called for each element of the array.
查看 scaladoc 了解更多详情
这篇关于查找数组的最小和最大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!