Skip to content

canJump

跳跃游戏 - 判断是否能从起点跳跃到终点。

输入配置

执行过程

步骤 1 / 4
开始跳跃游戏,初始maxReach=0
0
2
1
3
2
1
3
1
4
4
目标
最远可达: 0
当前位置
可到达
不可达

算法说明

跳跃游戏:使用贪心策略,维护最远可达位置maxReach。如果当前位置超过maxReach则无法到达。时间复杂度O(n),空间复杂度O(1)。

函数签名

typescript
function canJump(nums: number[]): boolean
function jump(nums: number[]): number

参数

参数名类型必填说明
numsnumber[]跳跃数组,nums[i]表示在位置i可跳跃的最大长度

返回值

类型说明
booleancanJump返回是否能到达最后位置
numberjump返回最少跳跃次数

工作原理

canJump

使用贪心策略:

  1. 维护当前能到达的最远位置maxReach
  2. 遍历数组,更新maxReach = max(maxReach, i + nums[i])
  3. 如果当前位置i > maxReach,说明无法到达

时间复杂度: O(n)
空间复杂度: O(1)

jump

记录跳跃边界currentEnd,到达边界时必须跳跃一次。

时间复杂度: O(n)
空间复杂度: O(1)