數組每個元素表示在該位置最多能向前跳躍的步數。判斷是否存在一種跳法能到達最後一個下標。
範例:
輸入: [2,3,1,1,4] → true
輸入: [3,2,1,0,4] → false
farthest = 當前能到達的最遠下標。i > farthest,說明卡住了,返回 false。farthest >= n-1,提前返回 true。farthest = max(farthest, i + nums[i])。class Solution:
def canJump(self, nums):
farthest = 0
n = len(nums)
for i in range(n):
if i > farthest:
return False
farthest = max(farthest, i + nums[i])
if farthest >= n - 1:
return True
return False