您的位置:首页 > 编程语言 > Python开发

LeetCode 55 Jump Game(Python 实现及详解)

2017-07-27 17:13 567 查看
Given an array of non-negative integers,you are initially positioned at the first index of the array.

 

Each element in the array represents yourmaximum jump length at that position.

 

Determine if you are able to reach the lastindex.

 

For example:

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

A = [3,2,2,0,4], return true.

题意:

给你一组正整数,数组里面数字表示该位置可以跳多少步。如果从第一个跳到最后那个数,就返回成功否则返回失败。

 

比如说A =[2,3,1,1,4]

默认位置为A[0],

方案一:A[0]往后最多跳2步--->A[2],A[2]能往后最多跳1步--->A[3],A[3]能往后最多跳1步--->A[4].(到了最后一个,无论该位置是多少都是True)

方案二: A[0]能往后跳1步--->A[1],A[1]跳3步--->A[4]

比如A = [3,2,1,0,4]

从默认位置A[0]能往后跳3步--->A[3],A[3] = 0也就是只能往后0个,不能到最后。经过多次尝试发现,无论如何不能到最后,则返回false

思路:

遍历数组,剩余步数step不为零的前提下,每次向前移动一步,将当前的num[i]和step相比较取较大者,作为剩余步数step。

【python 代码】

class Solution(object):

   def canJump(self, nums):

       """

       :type nums: List[int]

       :rtype: bool

       """

       step = nums[0]

       for i in range(1, len(nums)):

           if step > 0:

                step -= 1#默认向前走一步,即从i走到i+1,剩余步数减1

                step = max(step, nums[i])#将此位置步数与step作比较,最大值当做step

           else:

                return False

       return True

if __name__ == '__main__':

    S= Solution()

    A= [3,2,2,0,4]

   S.canJump(A)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Python