LeetCode: 45. Jump Game II

LeetCode: 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.

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

题目大意: 给定一个非负整数数组,每个数字代表其最大步长,求到达最后的 index 的最小步数。

解题思路

动态规划

dp[i] 表示到达 index = i 所需要的最小步数,则有转化方程:
dp[i] = min { dp[j]+1, .... } , 其中 0 <= j < i 且 nums[j] >= i - j;

代码如下:

class Solution {
public:
    int jump(vector<int>& nums) {
        // dp[i]: 到达 index = i 的位置的最小步数
        vector<int> dp;
        dp.resize(nums.size(), 0);

        for(int i = 0; i < nums.size()-1; ++i)
        {
            for(int j = 1; j <= nums[i]; ++j)
            {
                if(i+j < nums.size())
                {
                    if(dp[i+j] != 0) dp[i+j] = min(dp[i]+1, dp[i+j]);
                    else dp[i+j] = dp[i]+1;
                }
            }
        }

        return dp.back();
    }
};

很不幸,时间复杂度过高。 这个代码会 TLE

贪心

由于数组中给定的数字表示的是最大步长,因此,我们只需要记录每一步能到达的最远距离(maxDistance),以及下一步的可能最远距离(maxTouch),每次更新下一步可能的最大距离即可。

如图:
maxDIstance

时间复杂度 O(n), 空间复杂度 O(1)

AC代码

class Solution {
public:
    int jump(vector<int>& nums) {

        int maxDistance = 0;     // 记录上一步走的最大距离
        int nMinStep    = 0;     // 记录最小的步数
        int maxTouch    = 0;     // 记录这一步能到达的最大距离

        for(int i = 0; i < nums.size(); ++i)
        {
            if(maxDistance >= nums.size()-1) break;

            // 当上一步没有到达 i 时, 就该走这一步了。
            if(maxDistance < i)
            {
                ++nMinStep;
                maxDistance = maxTouch;
            }

            // 在第 index = i 时, 能达到的距离
            maxTouch = max(maxTouch, i + nums[i]);
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值