我有一个像这样的数组:
val a = Array(0, 6, 15, 0, 20, 0)
如果我使用reduceLeft
函数来查找该数组中的最小值,例如:
val f = (x: Int, y: Int) => x min y
val rlf = a.reduceLeft(f)
如何找到此数组中的最小数字(不包括与 0
的比较),因为在我的情况下,我使用 0
作为默认值,而不是我想要的值想比较吗?!
最佳答案
来源:
scala> val a = Array(0, 6, 15, 0, 20, 0)
a: Array[Int] = Array(0, 6, 15, 0, 20, 0)
scala> a.filterNot(_==0).min
res6: Int = 6
更新: 我错过了过滤器后数组为空的情况。所以正确的版本就像
a.filterNot(_==0) match {
case Array() => -1
case arr => arr.min
}
或
Try(a.filterNot(_==0).min).getOrElse(-1)
更新: 要获取索引最小值:
Try(a.zipWithIndex.filterNot(_._1 == 0).minBy(_._1)).getOrElse((-1,-1))
或者
a.zipWithIndex.filterNot(_._1==0) match {
case Array() => (-1,-1)
case arr => arr.minBy(_._1)
}
或(@Ryan 解决方案,对数组进行一次迭代)
a.foldLeft((-1, -1, 0)) {
case ((min, minInd, length), n) =>
if (n == 0) (min, minInd, length + 1)
else if (min > -1) {
val localMin = Math.min(min, n)
(localMin, if (localMin == min) minInd else length, length + 1)
}
else (n, length, length + 1)
}
使用“经典”循环来优化解决方案可能会更漂亮。
关于arrays - 求数组中除0之外的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31611734/