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.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
数组中每一个位置的数字代表可以往前跳跃的最大距离,判断根据数组中的数字能不能跳到最后一个位置
解法1:
设立一个标志位m表示在某个位置时候,获得的最大跳跃距离,如果m<i,则表示不能跳至此位置,失败
class Solution(object):
def canJump(self, nums):
m = 0
for i,n in enumerate(nums):
if i>m:
return False
m = max(m,i+n)
return True
解法2:
从最后一个元素往前遍历,每到一个位置时候判断前面位置的元素加上其值可否到达此位置
class Solution(object):
def canJump(self, nums):
goal = len(nums)-1
for i in range(len(nums)-1,-1,-1):
if i+nums[i]>=goal:
goal = i
return not goal