添加 0135.分发糖果.md Scala版本

This commit is contained in:
ZongqinWang
2022-06-13 20:53:11 +08:00
parent 2c1aa6ebf8
commit 32018ff79a

View File

@ -324,6 +324,31 @@ function candy(ratings: number[]): number {
}; };
``` ```
### Scala
```scala
object Solution {
def candy(ratings: Array[Int]): Int = {
var candyVec = new Array[Int](ratings.length)
for (i <- candyVec.indices) candyVec(i) = 1
// 从前向后
for (i <- 1 until candyVec.length) {
if (ratings(i) > ratings(i - 1)) {
candyVec(i) = candyVec(i - 1) + 1
}
}
// 从后向前
for (i <- (candyVec.length - 2) to 0 by -1) {
if (ratings(i) > ratings(i + 1)) {
candyVec(i) = math.max(candyVec(i), candyVec(i + 1) + 1)
}
}
candyVec.sum // 求和
}
}
```
----------------------- -----------------------