45. Jump 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.

数组中每一个值都是它能跳到的最远距离,例如第二个索引3,那么下一步最远可以往后跳三格。

我们可以每一次都选最远的那个跳,但是这个最远是下次能让我们跳到最远的那个。例如开始是2,那么它可以跳到3或者1,如果到3的话那么下次最远可以跳到索引4,但是1只能最远跳到索引3。

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        cur = 0
        pre = 0
        res = 0
        i=0
        while cur < len(nums)-1:
            res += 1
            pre = cur
            while i<=pre:
                cur=max(cur,i+nums[i])
                i+=1
        return res

我们用cur和pre来记录当前能跳到的最远索引和前一次能跳到的最远索引。开始都是0.进入循环后,每次记录加1代表跳了一次。然后先将cur赋值给pre,代表将上次的记录赋给了pre。然后计算这次能跳到的最远距离cur,注意这个时候我们的索引还没有跳,还是停留在上次的索引上。然后我们开始从上次的索引开始往后遍历试探,比如停留在的值是2,这个是最远能跳到的位置,我们需要尝试往后跳1,跳2,看跳到那个能让我再跳能跳到最远,那么我们cur就选这个。以下为例:

[2,3,1,1,4]

开始pre=0,cur=0.索引在2.然后进入第二个循环,因为此时指针还没动过,此时我们能跳到的最远就是n[2],然后进入第二轮循环。此时赋值pre=2,然后再计算cur最远能跳到哪,注意此时我们知道pre最远到2了,但是它也可以跳到n[1],所以我们需要搜索,看跳到n[1]会怎样,跳到n[2]会怎样。搜索后发现n[1]=3的时候能再跳到最远,那么就跳到n[1]。

要记得pre还是cur都是记录的最远能到的位置,真正跳的索引其实是i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值