mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 0135.分发糖果.md Scala版本
This commit is contained in:
@ -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 // 求和
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user