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.
给定一个非负整型数组,每个位置的数字代表在当前位置可以跳过的最大长度,初始化在0位置,判断能不能达到最后那个位置。
思路一:动态规划
首先想到的就是动态规划,很简单,保存i-1位置的所有可能到达情况。如果i-1位置所有情况组合加上对应位置的元素值大于i,则表明能该位置可以到达i。最终判断最后一个位置是否有解决方案。
Python 代码实现
class Solution:
def canJump(self, nums: List[int]) -> bool:
l = len(nums)
d = {}
if l == 1 and nums[0] == 0:
return True
if nums[0] < 1:
return False
# d里面存的是之前能到当前位置的所有位置
d[0]=[0]
for i in range(1,l):
lastArr = list(d[i-1])
if lastArr is None or len(lastArr) == 0:
return False
tmp = []
if i-1 not in lastArr:
if i-1+nums[i-1] >= i:
tmp.append(i-1)
for last in lastArr:
if last+nums[last] >= i:
tmp.append(last)
d[i]=tuple(tmp)
print(i," : ",tmp)
if d[l-1] is None or len(d[l-1]) == 0:
return False
return True
但是这种方法在极端最差的数组很长,且是降序情况下时间复杂度很高,无法AC。考虑优化
思路二:贪心算法
从最后一个位置向前遍历。如果当前位置加上对应的元素大于后一个位置,说明可以从这个位置到达后一个位置,并且更新最远位置lastPos为当前位置;否则保持lastPos不变。直到遍历到第一个位置,如果lastPos为0,则表明可以从0到达最后一个位置,否则表示0位置只能到达lastPos位置,后面的达到不了。
Python 代码实现
class Solution:
def canJump(self,nums):
lastPos = len(nums) - 1
for i in range(len(nums))[::-1]:
if (i + nums[i] >= lastPos) :
lastPos = i
return lastPos == 0
THE END.