zoukankan      html  css  js  c++  java
  • [leetcode] Jump Game II

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

    思路:

    好吧,又没做出来。最开始想法是和Jump Game一样,求出每个点所能到达的最远距离,如果某个点到达的最远距离比它前一个点的最远距离要大,就多跳一步到这个点。事实证明错的离谱。搜了搜博客,看了别人的思路,改进了一下自己的方法。

    之前的方法只要碰到能跳到更远的点,跳数加1,这样很多跳跃是浪费的。因此从,用maxlen代表某个点所能到达的最远距离,这个点就是跳跃的点。接下来就是在maxlen的范围内寻找下一次跳跃最远的那个点,因此本次就跳到这个点。以[2,3,1,1,4]为例,开始肯定在原点开始起跳,因此maxlen=0+2=2,这说明从A[0]只能跳到A[1]和A[2],具体跳到哪个由A[1]和A[2]两个点哪个跳的更远决定,如果到了A[1],接下来就可以跳到A[4];如果到A[2],接下来可以跳到A[3],因此我们选择跳到A[1]。如此直到某个点跳跃的最远距离超过了数组的范围,返回跳跃的次数。

    题解:

    class Solution {
    public:
        int jump(int A[], int n) {
            if(n==0 || n==1)
                return 0;
            int i=0;
            int minstep = 0;
            int maxlen = 0;
            while(i<n) {
                minstep++;
                maxlen = i+A[i];
                if(maxlen>=n-1)
                    return minstep;
                int tmp = maxlen;
                for(int j=i+1;j<=maxlen;j++)
                    if(j+A[j]>=tmp) {
                        tmp = j+A[j];
                        i = j;
                    }
            }
        }
    };
    View Code

    后话:

    最后还是把参考的一片博客给贴出来吧。

  • 相关阅读:
    如何重新加载 Spring Boot 上的更改,而无需重新启动服务器?
    什么是 JavaConfig?
    序列号Sequences
    包Packages
    参数Parameters、变量Variables
    maven配置多个镜像
    各种http报错的报错的状态码的分析
    举例说明同步和异步。
    第二阶段的任务及燃尽图(第二天)
    第二阶段的任务及燃尽图(第一天)
  • 原文地址:https://www.cnblogs.com/jiasaidongqi/p/4255252.html
Copyright © 2011-2022 走看看