leetcode上的Scala代码总是得到一个“编译超时”'错误。不知道如何处理它。甚至有时幸运地编译。提交结果仍然超过了时间限制'。这不是因为我的答案很耗时,而是在最简单的测试用例上失败了。 问题是' 135 Candy' 这是我的代码。
object Solution {
import scala.annotation.tailrec
def candy(ratings: Array[Int]): Int = {
candyLoop(ratings.toSeq, -1, 0,0, 0, 0)
}
@tailrec
def candyLoop(remains: Seq[Int],
tailValue: Int,
peekCandy:Int,
tailCandy: Int,
totalCandy: Int,
toPeek: Int
): Int = {
if (remains.isEmpty) {
totalCandy
} else {
//println(s"$tailValue : $tailCandy : $totalCandy : $toPeek")
val nextVal = remains.head
if (nextVal > tailValue) {
candyLoop(remains.tail,
nextVal,
tailCandy + 1,
tailCandy + 1,
totalCandy + tailCandy + 1,
0)
} else if (tailCandy > 1) {
candyLoop(remains.tail, nextVal,peekCandy, 1, totalCandy + 1, toPeek + 1)
} else {
val boost = if(peekCandy > toPeek + 1) toPeek else toPeek + 1
candyLoop(remains.tail, nextVal, peekCandy,1, totalCandy + boost + 1, toPeek + 1)
}
}
}
}