题目

https://leetcode-cn.com/problems/jump-game/

给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。

示例 1:

输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。

示例 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

解题思路

  • 贪心算法
  • 维护能到达的最远位置
  • 遍历列表
    • 如果当前位置不超过最远位置,就更新最远位置,如果超过列表末尾,则返回True
    • 如果当前位置超过最远位置,就返回False

代码

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        if not nums: return False

        max_pos = 0
        for i,n in enumerate(nums):
            if i > max_pos: 
                return False
                
            max_pos = max(max_pos, i+n)
            if max_pos >= len(nums)-1:
                return True
        
        return False

相关文章:

  • 2022-12-23
  • 2022-03-07
  • 2022-12-23
  • 2022-02-08
  • 2022-12-23
  • 2020-04-24
  • 2021-07-05
  • 2021-08-12
猜你喜欢
  • 2021-11-04
  • 2021-08-13
  • 2022-12-23
  • 2022-01-17
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案