[leetcode greedy]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.

数组中每一个位置的数字代表可以往前跳跃的最大距离,判断根据数组中的数字能不能跳到最后一个位置

解法1:

设立一个标志位m表示在某个位置时候,获得的最大跳跃距离,如果m<i,则表示不能跳至此位置,失败

1 class Solution(object):
2     def canJump(self, nums):
3         m = 0
4         for i,n in enumerate(nums):
5             if i>m:
6                 return False
7             m = max(m,i+n)
8         return True

解法2:

从最后一个元素往前遍历,每到一个位置时候判断前面位置的元素加上其值可否到达此位置

1 class Solution(object):
2     def canJump(self, nums):
3         goal = len(nums)-1
4         for i in range(len(nums)-1,-1,-1):
5             if i+nums[i]>=goal:
6                 goal = i
7         return not goal
8         
原文地址:https://www.cnblogs.com/fcyworld/p/6530203.html