LeetCode | 45. Jump Game II

82 篇文章 0 订阅
26 篇文章 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.)

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

思路一:动态规划,91/92 passed,超时

class Solution {
public:
    int jump(vector<int>& nums)
    {
        int len = nums.size();
        int dp[1000000] = {};
        dp[0] = 0;
        for(int i=1;i<len;i++)
            dp[i] = 999999;

        for(int i=0;i<len;i++)
        {
            for(int j=i+1;j<len && j<=i+nums[i];j++)
            {
                dp[j] = min(dp[j],dp[i]+1);
            }
        }

        return dp[len-1];
    }
};

思路二:BFS,改进后45ms AC

class Solution {
public:

    int _visit[1000000];

    struct cxk
    {
        int _index;
        int step;

        cxk(int a,int b)
        {
            _index = a;
            step = b;
        }
    };

    int jump(vector<int>& nums)
    {
        int len = nums.size();
        queue<cxk> q;
        q.push(cxk(0,1));
        _visit[0] = 1;
        int it_max = 1;     //当前开始遍历的下标首地址
        while(!q.empty())
        {
            cxk tmp = q.front();
            q.pop();
            if(tmp._index == len-1) //已经走到最后一步
            {
                return tmp.step-1;
            }

            for(int i=it_max;i<len && i<=tmp._index+nums[tmp._index];i++)
            {
                if(_visit[i] == 0)
                {
                    q.push(cxk(i,tmp.step+1));
                    _visit[i] = 1;
                }
            }
            it_max = tmp._index+nums[tmp._index]+1;     //已经找过的下标就不用再找了
        }
        return -1;
    }
};

思路三:类似BFS,不用queue就能实现,直接模拟
19ms AC

class Solution {
public:
    int jump(vector<int>& nums)
    {
        int n = nums.size(), step = 0, start = 0, end = 0;
        while (end < n - 1)
        {
            step++;
            int maxend = end + 1;
            for (int i = start; i <= end; i++) {
                if (i + nums[i] >= n - 1)
                    return step;
                maxend = max(maxend, i + nums[i]);
            }
            start = end + 1;
            end = maxend;
        }
        return step;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值