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 };
  • 相关阅读:
    ceph中pool的管理
    ubuntu 16.04安装ceph集群(双节点)
    win7设置开机启动virtualBOX虚拟机
    Linux Linux程序练习十九
    Linux Linux程序练习十八
    Linux Linux程序练习十七
    Linux 网络编程详解十二
    Linux socket多进程服务器框架三
    Linux socket多进程服务器框架二
    Linux socket多进程服务器框架一
  • 原文地址:https://www.cnblogs.com/soyscut/p/3775315.html
Copyright © 2011-2022 走看看