【Leetcode】45. Jump Game II 跳跃游戏 II

最小跳跃次数算法解析
本文介绍了一种解决数组中寻找从起始位置到达末尾所需的最小跳跃次数的问题算法。通过迭代更新跳跃范围,该算法有效地找到了达到目标的最短路径。示例中,输入数组[2,3,1,1,4]的最小跳跃次数为2,具体步骤包括从索引0跳至索引1,再从索引1跳至最后位置。

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.

解法

参考评论区@tonyfirst1解法

[l,r)是需要至少ans次跳跃才能到达的地方:

  1. r>=n时,已经跳到终点了,输出ans
  2. r<n时,分析每个i in xrange(l,r),第ans+1次跳跃能到达的最远下标为:farmost=max(i+nums[i] for i in xrange(l,r)),那么至少需要ans+1次跳跃才能到达的地方就是[r,farmost+1)

[l,r)里的每个下标都可以通过ans次跳跃到达,因为(1)第一次的时候满足条件(2)当[l,r)满足条件时,假设farmost=i+nums[i],由于步数小于等于nums[i]的地方都可以跳,所以[i,i+nums[i]]都是可以到达的,而[r,i+nums[i]+1)一定包含在[i,i+nums[i]]里,所以一定可以到达。

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l,r,ans = 0,1,0
        n = len(nums)-1
        while n>=r:
            ans += 1
            l,r = r, max(j+nums[j] for j in xrange(l,r))+1
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值