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.
Answer
如果 index = 0 的格子沒有辦法被跳過去,就會停住 STOP
1. 如果 index = 0 時,去檢查前面的 index 有沒有夠大
2. 一直到沒有 index 了還是不夠大 -> return False
class solution:
def canJump(self, nums):
# if it never get into 0, then it will always reach the last index
for i in range( 0,len(nums)-1 ):
# the step = 0
if nums[i] == 0:
# if there is another way to skip this index
for x in range( i-1, -2, -1 ):
# NO
if ( x < 0):
return False
# YES
elif ( nums[x] > ( i-x ) ):
break
return True