4.25python Leetcode 45

本文探讨了Jump Game II问题的解决方案,采用贪心算法实现了寻找最少跳跃次数以达到数组末尾的目标。

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

45Jump Game II

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.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

You can assume that you can always reach the last index.

class Solution(object):
    def jump(self, nums):
        if len(nums) == 1:
            return 0
        ans = 0
        start = 0
        while start < len(nums) and start + nums[start] < len(nums) - 1:
            tmp_list = nums[start + 1: start + nums[start] + 1]
            i = 0
            max_jump = 0
            max = 0
            while i < nums[start]:
                if start + i + 1 + tmp_list[i] > max_jump and nums[start + i + 1 + tmp_list[i]]:
                    max = i + start + 1
                    max_jump = start + i + 1 + tmp_list[i]
                i += 1
            start = max
            ans += 1
        return ans + 1

        
        """
        :type nums: List[int]
        :rtype: int

 题解:

题目是给定一个列表nums, 给定下标i, nums[i]表示能从这个地方前进的最大步数。

现在从下标0开始,求到最后一个下标的最小步数。

第一想法是用动态规划,即用一个所有值均为无限大的数组step,用于存到这个位置所用的最小步数。

那么对于每一个i, k <= nums[i], step[i+k] = min(step[i] + 1, step[i+k])

但是发现会超时,仔细一想最坏的情况是O(n平方)的。

因此,换一个想法,使用贪心算法。

即对于一个当前位置i, 只需要找到他的下2跳能到的最远的位置即可。

即下一个位置应该为j = max{i + k + nums[i + k], 1 <= k <= nums[i] }

当然,要证明这一点。倘若存在一个这样的m不满足这个等式,即m < j,但是通过这个m的到达终点的步数更少。

那么在对于取定这个j的k,在下一跳的位置i+k中,根据算法的定义是一定不会漏掉这个m的,因此矛盾。

所以这个算法是可行的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值