Leetcode 55. Jump Game
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.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
我一开始认为这是一道DP的题目。其实,可以维护一个maxReach,并对每个元素更新这个maxReach = max(maxReach, i + nums[i])。注意如果 i>maxReach,说明从起点开始能跳到的最远距离不到i, 所以i后面的点也就无法到达了。另外如果 maxReach >= n-1 说明已经可以跳到终点了,之后的点也就不用继续检查了。
1 class Solution(object): 2 def canJump(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: bool 6 """ 7 n = len(nums) 8 maxReach = 0 9 10 for i in range(n): 11 if i>maxReach or maxReach >= n-1: 12 break 13 maxReach = max(maxReach, i+nums[i]) 14 15 if maxReach < n-1: 16 return False 17 else: 18 return True