mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
添加 0045.跳跃游戏II.md Scala版本
This commit is contained in:
@ -279,7 +279,31 @@ function jump(nums: number[]): number {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Scala
|
||||||
|
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
def jump(nums: Array[Int]): Int = {
|
||||||
|
if (nums.length == 0) return 0
|
||||||
|
var result = 0 // 记录走的最大步数
|
||||||
|
var curDistance = 0 // 当前覆盖最远距离下标
|
||||||
|
var nextDistance = 0 // 下一步覆盖最远距离下标
|
||||||
|
for (i <- nums.indices) {
|
||||||
|
nextDistance = math.max(nums(i) + i, nextDistance) // 更新下一步覆盖最远距离下标
|
||||||
|
if (i == curDistance) {
|
||||||
|
if (curDistance != nums.length - 1) {
|
||||||
|
result += 1
|
||||||
|
curDistance = nextDistance
|
||||||
|
if (nextDistance >= nums.length - 1) return result
|
||||||
|
} else {
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user