1 """
2 Given an array of non-negative integers, you are initially positioned at the first index of the array.
3 Each element in the array represents your maximum jump length at that position.
4 Determine if you are able to reach the last index.
5 Example 1:
6 Input: [2,3,1,1,4]
7 Output: true
8 Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
9 Example 2:
10 Input: [3,2,1,0,4]
11 Output: false
12 Explanation: You will always arrive at index 3 no matter what. Its maximum
13 jump length is 0, which makes it impossible to reach the last index.
14 """
15 """
16 自己AC。用一个dp数组来保存能否到达该位置
17 """
18 class Solution1:
19 def canJump(self, nums):
20 dp = [False]*len(nums)
21 dp[0] = True
22 temp2 = 0
23 for i in range(len(nums)-1):
24 if dp[i] == True:
25 temp1 = max(i+1, temp2) #如果这里写成temp1=i+1会超时,重复赋值了
26 temp2 = min(i+nums[i], len(nums)-1)
27 while temp1 <= temp2:
28 dp[temp1] = True
29 temp1 += 1
30 return dp[-1]
31 """
32 解法二:从后向前遍历 O(n)解法
33 """
34 class Solution2:
35 def canJump(self, nums):
36 last = len(nums)-1
37 i = last - 1
38 while i >= 0:
39 if(nums[i] + i) >= last:
40 last = i
41 i -= 1
42 return last <= 0
43
44 if __name__ == '__main__':
45 ans = Solution2()
46 nums = [2, 3, 1, 1, 4]
47 print(ans.canJump(nums))