LeetCode 55 Jump Game (Python)

Posted by 小明MaxMing on April 26, 2020

题目

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.

解题思路

如果一个格子可以跳到,那么在这个格子之前的所有格子都能跳到,所以就直接贪心,遍历每个格子看最远能跳到的格子,如果当前已经位置已经超过最远能跳到的位置,则返回False,如果已经跳到了最后一个格子返回True

代码

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        reach = 0
        for i, n in enumerate(nums):
            if i > reach:
                return False
            reach = max(reach, i + n)
        return True

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅