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

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

思路

本质上是一道用贪心算法解决的题目,但是从实现上来看却感觉是动态规划的变种:我们维护一个当前可以到达的最远位置,以及一个一维数组(记录从首元素跳到该位置元素所需的最少步数),然后遍历nums中的每个元素,一旦通过它可以跳到更远的位置,则更新当前最远位置到更远位置之间的最少步数。一旦发现最远位置到达末尾或者越界,则可以立即返回。

我感觉对本题目的时间复杂度分析可能是面试官感兴趣的另一考点:虽然从实现上来看,里面存在两重循环,但实际的时间复杂度却是O(n)。这是因为:在我们对nums中的元素做遍历的过程中,所有更新的区间是不重合的,而且这些区间刚好完整覆盖了整个数组空间,所以总和是n。

代码

class Solution {
public:
    int jump(vector<int>& nums) 
    {
        if(nums.size() == 0)
            return 0;
        vector<int> step(nums.size(), 0);
        int max_reach = 0;
        for(int i = 0; i < nums.size(); ++i)
        {
            int tem = nums[i] + i;                          // the maximum index one can reach from i
            if(max_reach < tem)
            {
                tem = min(tem, (int)nums.size() - 1);       // avoid overflow
                for(int j = max_reach + 1; j <= tem; ++j)   // we can reach [max_reach + 1, tem] in fewer steps
                    step[j] = step[i] + 1;
                max_reach = tem;
                if(max_reach >= nums.size() -1)             // we alrady reach the last element
                    break;
            }
        }
        return step[nums.size() - 1];
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值