zoukankan      html  css  js  c++  java
  • 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.

    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.

    AC code:

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

    Runtime: 16 ms, faster than 22.35% of C++ online submissions for Jump Game II.

    BFS:

    class Solution {
    public:
        int jump(vector<int>& nums) {
            int steps =1, i, curEnd = 0, newEnd=0, len = nums.size();
            if(len<=1) return 0;
            for(i=0; i<=curEnd; ++i)
            {
                newEnd = max(newEnd, i+nums[i]);
                if(newEnd>=(len-1)) return steps;
                if(i==curEnd)  // end of the current level, move to the next level
                {
                    curEnd = newEnd;
                    ++steps;
                }
            }
            return INT_MAX; // curEnd = newEnd, can not reach the end
        }
    };
    

    Runtime: 8 ms, faster than 98.58% of C++ online submissions for Jump Game II.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    贡献15本经典C、C++、MFC、VC++教程,都是pdf完整版的
    雪花
    孙鑫C++视频教程 rmvb格式 全20CD完整版 精品分享
    mac上用VMWare虚拟机装win7
    阿里云如何解析域名,搭建云服务器环境
    2. Windows编程基础
    复制指定目录下的全部文件到另一个目录中
    Select查询命令
    使用OneNote2016发送博客
    Linux数字雨
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9802974.html
Copyright © 2011-2022 走看看