arrays - 求数组中除0之外的最小值

标签 arrays scala vector

我有一个像这样的数组:

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/

相关文章:

arrays - 你能在 Postgres 中索引数组的元素吗?

scala - 如何创建一个只接受可以使用 spray-json 转换为 Json 的类型的函数

scala - 更改 build.sbt 以使 ScalaTest 测试能够与 Scala Play 一起运行

c++ - 插入元素后 vector 的容量增加?

c++ - STL 中的 vector 与列表

c - 对于数组,为什么会出现 a[5] == 5[a] 的情况?

javascript - 无法从日期对象javascript获取日期和月份

c++ - 来自 std::wstring 的 Asisgn LPCWSTR 数组

sql - 包含 greaterThanEqual (gte) 或 lessThanEqual (lte) 的 Squeryl 查询给出错误/无结果

C++:检查 vector 中所有对象属性的值