Problem
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.
Solution
两种思路:
一、从左到右计算列表右起点开始可以到达的最远距离。
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_reach, n = 0, len(nums)
for i, x in enumerate(nums):
if max_reach < i:
return False
if max_reach >= n - 1:
return True
max_reach = max(max_reach, i + x)
二、遍历列表,计算每个位置上最多往能往右边跳跃多少步(有可能是从本身位置跳,也有可能是从该位置的左边跳过去的),如果不能再往后边跳了,那就说明无法到达最后一格
class Solution:
def canJump(self, nums: List[int]) -> bool:
stepsLeft = nums[0]
if not stepsLeft and len(nums) > 1:
return False
for num in nums[1:-1]:
stepsLeft = max(stepsLeft - 1, num)
if not stepsLeft:
return False
return True