Leecode 0055. Jump Game
55. Jump Game
You are given an integer array nums
. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
Example 1:
1 | Input: nums = [2,3,1,1,4] |
Example 2:
1 | Input: nums = [3,2,1,0,4] |
题目大意
给定一个整数数组 nums
,初始位置在数组的第一个索引(索引 0)。数组中的每个元素表示在该位置可以跳跃的最大长度。判断是否能够到达最后一个索引(数组的最后一个位置),返回 true
或 false
。
例如:
- 输入
nums = [2,3,1,1,4]
,输出true
(从索引 0 跳 1 步到索引 1,再跳 3 步到最后索引); - 输入
nums = [3,2,1,0,4]
,输出false
(无论如何都会到达索引 3,但其最大跳跃长度为 0,无法到达最后索引)。
解题思路
核心思路是贪心算法,通过跟踪 “当前可到达的最远位置”,判断是否能覆盖到最后一个索引:
- 贪心策略:
遍历数组时,实时更新从当前位置及之前所有位置能到达的最远索引(max_reach
)。若在遍历过程中,max_reach
已覆盖最后一个索引,则直接返回true
;若遍历到某个位置时,该位置超出了max_reach
(即无法到达该位置),则返回false
。 - 关键逻辑:
max_reach
表示当前能到达的最远索引,初始值为 0;- 对于每个位置
i
,更新max_reach = max(max_reach, i + nums[i])
(从位置i
能跳到的最远位置); - 若
max_reach >= n-1
(n
为数组长度),说明已能到达最后一个索引,返回true
; - 若
i > max_reach
,说明当前位置i
无法到达,后续位置更无法到达,返回false
。
代码实现
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.