Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
看是否能达到最后一个点。
记录好每次可以到达的最远距离,如果最远距离>=len(nums)直接返回True。
while的条件可以改变。(for循环的时候i不能改)
class Solution:
def canJump(self, nums: List[int]) -> bool:
reach=nums[0]
i=0
while i<=reach:
reach=max(i+nums[i],reach)
if reach>=len(nums)-1:
return True
i+=1
return False

本文探讨了如何解决一个特定的算法问题:给定一个非负整数数组,每个元素代表从该位置能跳的最大长度,判断是否能跳到最后一个元素。通过记录可达的最远距离,使用while循环优化解决方案。
402

被折叠的 条评论
为什么被折叠?



