zoukankan      html  css  js  c++  java
  • Leetcode::JumpGame

    Description:

    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.

    Determine if you are able to reach the last index.

    For example:
    A = [2,3,1,1,4], return true.

    A = [3,2,1,0,4], return false.

    分析: 此题上来直接的解法,是建一个bool的vector,然后从每一点出发,按照该点的值来更新后面的vector里面的bool值

    然后看最后一点是否为false. 

    这样当然是可以的,但是这样每一点都要往后遍历此点值步,最坏情况时 n+n-1 + n-2 +... +1,即O(n^2),最终会超时。

    所以我们要建立的遍历一遍就能得到结果的方法。其方法很简单:维护一个maxstep变量,即当前点及之前所有点能够前进的最大值,

    这个值每步更新为 maxstep = max(maxstep-1,A[i]); 这个值在前进道最后的点之前变为0,则结果为false.

    贴上两种算法:

     1 //Faster version
     2 class Solution {
     3 public:
     4     bool canJump(int A[], int n) {
     5         
     6         int maxrec = 1;
     7         
     8         for(int i=0;i<n;i++)
     9         {
    10             maxrec--;
    11             if(i==n-1) return true;
    12             maxrec = max(maxrec,A[i]);
    13             if(maxrec==0)
    14                 break;
    15         }
    16         return false;
    17     
    18     }
    19 };
     1 //TLE version
     2 class Solution {
     3 public:
     4     bool canJump(int A[], int n) {
     5         vector<bool> rec(n,false);
     6         rec[0] = true;
     7         for(int i=0;i<n;i++)
     8         {
     9             if(!rec[i]) continue;
    10             
    11             int step = A[i];
    12             for(int j=0;j<=step;j++)
    13             {
    14                 rec[min(i+j,n-1)]=true;
    15                 if(rec[n-1])
    16                     return true;
    17             }
    18         }
    19         
    20         return rec[n-1];
    21     
    22     }
    23 };
  • 相关阅读:
    __dict__
    谷歌浏览器如何清除当前页面的缓存
    博客园插入超链接时如何取消下划线
    杂七杂八
    博客园首页如何添加 Live 2D 模型
    访问 IIS 元数据库失败 的解决方法 .
    VS 关于无法打开项目文件,此安装不支持该项目类型的问题
    汉字转为unicode
    Windchill 预览效果偏向左边
    MD04
  • 原文地址:https://www.cnblogs.com/soyscut/p/3775315.html
Copyright © 2011-2022 走看看