LeetCode:55. Jump Game

博客围绕LeetCode 55. Jump Game展开,给定非负整型数组,需判断能否从0位置到达最后位置。先介绍动态规划思路,保存i - 1位置所有可能到达情况来判断i位置能否到达,但极端情况时间复杂度高。后提出贪心算法,从后向前遍历更新最远位置,以此判断能否到达。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode: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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.
             

给定一个非负整型数组,每个位置的数字代表在当前位置可以跳过的最大长度,初始化在0位置,判断能不能达到最后那个位置。

思路一:动态规划

首先想到的就是动态规划,很简单,保存i-1位置的所有可能到达情况。如果i-1位置所有情况组合加上对应位置的元素值大于i,则表明能该位置可以到达i。最终判断最后一个位置是否有解决方案。

Python 代码实现

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        l = len(nums)
        d = {}
        if l == 1 and nums[0] == 0:
            return True
        if nums[0] < 1:
            return False
        
        # d里面存的是之前能到当前位置的所有位置
        d[0]=[0] 
        
        for i in range(1,l):
            lastArr = list(d[i-1])
            if lastArr is None or len(lastArr) == 0:
                return False

            tmp = []
            if i-1 not in lastArr:
                if i-1+nums[i-1] >= i:
                    tmp.append(i-1)
            for last in lastArr:
                if last+nums[last] >= i:
                    tmp.append(last)
            d[i]=tuple(tmp)
            print(i," : ",tmp)
        
        if d[l-1] is None or len(d[l-1]) == 0:
            return False
        return True

但是这种方法在极端最差的数组很长,且是降序情况下时间复杂度很高,无法AC。考虑优化

思路二:贪心算法

从最后一个位置向前遍历。如果当前位置加上对应的元素大于后一个位置,说明可以从这个位置到达后一个位置,并且更新最远位置lastPos为当前位置;否则保持lastPos不变。直到遍历到第一个位置,如果lastPos为0,则表明可以从0到达最后一个位置,否则表示0位置只能到达lastPos位置,后面的达到不了。

Python 代码实现

class Solution:
    def canJump(self,nums):
        lastPos = len(nums) - 1
        for i in range(len(nums))[::-1]:
            if (i + nums[i] >= lastPos) :
                lastPos = i
        return lastPos == 0

THE END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值