本文共 872 字,大约阅读时间需要 2 分钟。
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: trueExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]Output: falseExplanation: 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
转载地址:http://tcrbb.baihongyu.com/