题目描述:
思路:
贪心算法。我们遍历一遍数组,在保证当前位置可达的基础上,寻找能到达的最远距离。最后,如果能到达的最远的距离大于等于最后一个数组位置,返回True。否则返回False。
代码与注释:
class Solution:
def canJump(self, nums: List[int]) -> bool:
# 遍历数组,看每一步能够到达的最远距离
reach_max_position = nums[0]
for i in range(len(nums)-1):
# 得保证当前位置是前一步可达的!
if i <= reach_max_position:
reach_max_position = max(reach_max_position, i + nums[i])
if reach_max_position >= len(nums)-1:
return True
else:
return False