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 说明已经可以跳到终点了,之后的点也就不用继续检查了。

 class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n = len(nums)
maxReach = 0 for i in range(n):
if i>maxReach or maxReach >= n-1:
break
maxReach = max(maxReach, i+nums[i]) if maxReach < n-1:
return False
else:
return True
上一篇:OpenLayer


下一篇:jQuery实现动态添加和删除一个div