zoukankan      html  css  js  c++  java
  • [Leetcode] jump game 跳跃游戏

    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], returntrue.

    A =[3,2,1,0,4], returnfalse.

     题意:给定以非零整数组成的数组,每个值代表可以跳过的距离,问能否到达最后

    思路:找到某一时刻能到达的最远距离maxlen,若该值大于等于n-1说明从这个地方能够直接跳到最后;若当前数组中的值为0,而最大值maxlen不能跳过这个点说明不能达到最后;一般情况是,当前数组元素的下标加上对应值和maxlen对比,若大于则更新maxlen。代码如下:

     1 class Solution {
     2 public:
     3     bool canJump(int A[], int n) 
     4     {
     5         if(n==0)    return true;
     6         
     7         int maxLen=A[0];
     8         for(int i=0;i<n;++i)
     9         {
    10             if(maxLen>=n-1)
    11                 return true;
    12             else if(A[i]==0&&maxLen<=i)
    13                 return false;
    14             else
    15                 maxLen=max(i+A[i],maxLen);
    16         }
    17         return false; 
    18     }
    19 };

    还有一种思路是:定义一个当前等达到的最大距离maxlen,那该值之前的所有点都是可以达到的,在遍历之前的这些点的过程中,更新最远距离maxlen。我们可以通过最远距离是否等于n来判断(当然这个距离要不大于n)。参考这里。代码如下:

     1 class Solution {
     2 public:
     3     bool canJump(int A[], int n) 
     4     {
     5         int maxLen=0;
     6         int i=0;
     7         for( ;i<=maxLen&&i<n;++i)
     8         {
     9             if(maxLen>=n)  //不加if判断也可
    10                 return true;
    11             maxLen=max(maxLen,i+A[i]);
    12         }
    13         return (i==n);
    14     }
    15 };
  • 相关阅读:
    60阶单群同构于A5的证明
    Riemann映射定理
    一个特殊情形的Mittag-Leffler分解
    一个重要的函数
    指数有限的子群存在一个右陪集代表元系,同时也是左陪集代表元系
    素数的平方阶群必为Abel群
    $mathscr{F}$类
    一个多项式问题
    Mittag-Leffler定理,Weierstrass因子分解定理和插值定理
    C -Concatenating Teams (字符串hash)
  • 原文地址:https://www.cnblogs.com/love-yh/p/7168914.html
Copyright © 2011-2022 走看看