0.原题
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.
1.代码
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
farthest = nums[0]
destination = len(nums)-1
for i in range(destination):
if nums[i] == 0:
if farthest <= i:
return False
else:
if farthest < i + nums[i]:
farthest = i + nums[i]
return True
2.思路
首先,不能到达终点的情况是:困在了某个等于0的点,即这个点之前的所有点都无法跨过这个点。
这个很好理解,若nums中无零点,一步一步走就可以到达终点;如果有零点,在零点之前,步子大一点,跨过零点即可。
因此,我们使用for循环:
当前位置坐标index+nums[index]就是,从index点出发,能够到达最远的距离。
如果碰到0点,就判断一下:之前的所有点,能够到达的最远距离,是否可以跨过这个0点即可。