LeetCode: Jump Game II [044]

151 篇文章 0 订阅

【题目】


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.

For example:
Given array A = [2,3,1,1,4]

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.)



【题意】

给定一个正数数组,每一位上的数值表示最大的跳转步数。问从第一位跳到最后一位最少需要跳多少步。


【思路】

       

        从前往后依次确定跳转到各给位置上所需要的最少步数。
        以题设中的A数组为例
        先来看A[0]=2, 意味着从0位置我们可以跳转到1或者2位置,反过来讲,也即跳转到位置1和2最少只需要跳1步就可以了。
        再来看A[1]=3, 意味着从1位置我们可以跳转到2,3,4这3个位置,由于从起点跳转到位置1最少需要1步,这么来说,跳转到位置2,3,4的最少步数数就是在2。需要注意的是,在上一步中我们已经确定了跳转到2的最小步数是1,显然跳两步是不必要的。因此只需要更新跳转到位置3,4的步数为2即可。也就是说我们我们只需要对那些还未标记为可达的节点(即还未确定跳转步数的节点)进行更新。
        数组中其他位置的跳转步数依次类推。


【代码】

class Solution {
public:
    int jump(int A[], int n) {
        int result;
        if(n<2)return 0;
        int*steps=new int[n];
        steps[0]=0;
        int pos=1;      //指向还没标记跳转步数的区域的第一个位置,初始是1,即第2个位置(1是索引位)。
        for(int i=0; i<n-1; i++){
            while(pos<n&&pos<=i+A[i]){
                steps[pos++]=steps[i]+1;
            }
            if(pos==n)break;
        }
        result=steps[n-1];
        delete steps;           //记得释放空间
        return result;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值