我有一个数组,我想在迭代数组时找到收到的第一个最大值。
0,2,3,0,1,2,3,4,5
因此,在这种情况下,只要3小于0,循环就应该中断,输出应该是3。
输出应为:
3
您还没有说明如何处理空集合。Option
是一个很好的解决方案。
def firstPeak(ints :Iterable[Int]) :Option[Int] =
ints.sliding(2)
.find(pair => pair.head > pair.last)
.fold(ints.lastOption)(_.headOption)
firstPeak(Array.empty) //res0: Option[Int] = None
firstPeak(Vector(9)) //res1: Option[Int] = Some(9)
firstPeak(Array(0,2,3,0,1,2,3,4,5)) //res2: Option[Int] = Some(3)
firstPeak(List(0,2,3,10,11,12,13,14,15)) //res3: Option[Int] = Some(15)
以下是使用List的递归方法
def findTopMax(list: List[Int]): Option[Int] = {
@annotation.tailrec
def loop(remaning: List[Int], currentMax: Int): Int =
remaning match {
case x :: _ if (x > currentMax) =>
currentMax
case xs :: xs =>
loop(remaning = xs, currentMax = x)
case Nil =>
currentMax
}
list match {
case x :: xs => Some(loop(remaning = xs, currentMax = x))
case Nil => None
}
}
这里有一个"循环">(从技术上讲,这也是一个递归(,使用ArraySeq(这是一个不可变的数组,如果你喜欢或在2.12
中,你可以使用普通数组(
import scala.collection.immutable.ArraySeq
def findTopMax(array: ArraySeq[Int]): Option[Int] = {
val length = array.length - 1
@annotation.tailrec
def loop(idx: Int, currentMax: Int): Int =
if (idx == length) currentMax
else if (array(idx) > currentMax) currentMax
else loop(idx = idx + 1, currentMax = array(idx))
if (length == -1) None
else loop(idx = 1, currentMax = array(0))
}
诀窍是,您可以随时中断递归。