您的位置:首页

LeetCode Jump Game

2017-07-17 12:57 330 查看

LeetCode解题之Jump Game

原题

数组中的每一个值表示在当前位置最多能向前面跳几步,推断给出的数组是否否存在一种跳法跳到最后。

注意点:

全部的数字都是正数

跳的步数能够比当前的值小

样例:

输入: nums = [2, 3, 1, 1, 4]

输出: True

输入: nums = [3, 2, 1, 0, 4]

输出: False

解题思路

先想一下什么时候不能够完毕跳跃,在当前位置之前(包含当前位置)能够跳跃到的最远距离就是当前位置,且这时候还没有到终点;什么样的情况就能保证能够跳到终点呢,仅仅要当前最远距离超过终点就可以。仅仅要当前的位置没有超过能跳到的最远距离,就能够不断的刷新最远距离来继续前进。

AC源代码

class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
length = len(nums)
index = 0
longest = nums[0]
while index <= longest:
if longest >= length - 1:
return True
longest = max(longest, index + nums[index])
index += 1
return False

if __name__ == "__main__":
assert Solution().canJump([2, 3, 1, 1, 4]) == True
assert Solution().canJump([3, 2, 1, 0, 4]) == False


欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: