跳跃游戏 II
Jump Game II
本机进度仅保存在当前浏览器
题目描述
给定一个长度为 n 的 0 索引整数数组 nums,初始位置为 nums[0],每个元素代表在该位置可以跳跃的最大长度,目标是到达数组最后一个位置并使用最少的跳跃次数(数据保证可达)。
示例:nums = [2, 3, 1, 1, 4],输出 2(跳到下标 1,再跳 3 步到末尾)。
解题思路
- 把跳跃想成 BFS 分层:每次跳跃覆盖一个连续可达区间,层与层之间由"本层能延伸到的最远点"衔接。
- 维护当前层的边界 cur_end 与下一步可达的最远点 farthest:扫描到 i == cur_end 时不得不起跳,次数加一并把边界推到 farthest。
- 贪心正确性:在边界前任意选择都不会比"覆盖到 farthest"更优,因为 farthest 已是两层之内的极限。
参考实现
查看参考实现Python · 建议先自行作答
def jump(nums):
steps = cur_end = farthest = 0
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
# 走到当前层边界,必须再跳一次
if i == cur_end:
steps += 1
cur_end = farthest
return steps