diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index 9e61fbb8..648355fd 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -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 + } +} +``` diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index 6fa83495..e7c4f5a2 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -193,7 +193,22 @@ function canJump(nums: number[]): boolean { }; ``` - +### Scala +```scala +object Solution { + def canJump(nums: Array[Int]): Boolean = { + var cover = 0 + if (nums.length == 1) return true // 如果只有一个元素,那么必定到达 + var i = 0 + while (i <= cover) { // i表示下标,当前只能够走cover步 + cover = math.max(i + nums(i), cover) + if (cover >= nums.length - 1) return true // 说明可以覆盖到终点,直接返回 + i += 1 + } + false // 如果上面没有返回就是跳不到 + } +} +``` -----------------------