From b0664fcb81c475356ddf925b839df6e00c434e8a Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sat, 11 Jun 2022 17:21:03 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200055.=E8=B7=B3?= =?UTF-8?q?=E8=B7=83=E6=B8=B8=E6=88=8F.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0055.跳跃游戏.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index 17a3b4f4..345f8eba 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 // 如果上面没有返回就是跳不到 + } +} +``` ----------------------- From 74a422c53b2817271b8f50a61bdd8ccdf77a5e25 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sat, 11 Jun 2022 20:03:12 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200045.=E8=B7=B3?= =?UTF-8?q?=E8=B7=83=E6=B8=B8=E6=88=8FII.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0045.跳跃游戏II.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index 4e3ab24a..f2940361 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 + } +} +```