跳跃游戏
Jump Game
本机进度仅保存在当前浏览器
题目描述
给你一个非负整数数组 nums,你最初位于数组的第一个下标。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标。
示例:nums = [2, 3, 1, 1, 4],输出 true;nums = [3, 2, 1, 0, 4],输出 false。
解题思路
- 维护"当前能到达的最远下标" farthest,从左向右扫描。
- 若下标 i 超出 farthest,说明 i 不可达且右侧更不可达,返回 false;否则用 i + nums[i] 更新 farthest。
- farthest 覆盖末尾即成功;扫描一趟即可,本质是贪心式区间扩展。
参考实现
查看参考实现Python · 建议先自行作答
def canJump(nums):
farthest = 0
for i, step in enumerate(nums):
if i > farthest:
return False
farthest = max(farthest, i + step)
return farthest >= len(nums) - 1