zoukankan      html  css  js  c++  java
  • 45. Jump Game II

    Problem:

    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.

    思路

    采用BFS算法。每次计算出能到达的最远距离reach,则下一次的end为reach,start为上一次的end+1,保存能够到达的区域[start, end],然后判断是否能到达终点。

    Solution (C++):

    int jump(vector<int>& nums) {
        if (nums.empty())  return 0;
        int n = nums.size(), step = 0, start = 0, end = 0, reach;
        
        while (end < n-1) {
            step++;
            reach = end + 1;
            
            for (int i = start; i <= end; ++i) {
                if (i + nums[i] >= n-1)  return step;
                reach = max(reach, i + nums[i]);
            }
            start = end + 1;
            end = reach;
        }
        return step;
    }
    

    性能

    Runtime: 12 ms  Memory Usage: 10.2 MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    vim编辑器和bash算术运算入门
    vim编辑器
    egrep及文本处理工具
    grep与基本正则表达式
    bash脚本编程基础及配置文件
    博客开通了
    测试用例考虑因素
    地图测试点的总结
    app测试的case点(2)
    App 99.9%稳定
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12290720.html
Copyright © 2011-2022 走看看