• Jump Game <leetcode>


    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.

    算法:首先看能一次性到达最后一点的点,比如2,3,1,1,4,  能到达A[4]的是A[1],A[3],此时A[1]肯定也能到达A[1]后面所有的点,所以把A[1],当做关键点,向前知道到达第一个节点。也可以把A[3]当做关键点,因为当数据很多时,找右侧的第一个点比较容易,找左边第一个点比较费时。两个代码如下:

     1 //  52ms
     2 
     3 
     4 class Solution {
     5 public:
     6     bool canJump(int A[], int n) {
     7         if(n==1)  return true;
     8         else
     9         {
    10             for(int i=0;i<=n-2;i++)
    11             {
    12                 if(A[i]+i>=n-1)
    13                 {
    14                     return canJump(A,i+1);
    15                 }
    16             }
    17             return false;
    18         }
    19     }
    20 };
     1 //44ms
     2 
     3 
     4 class Solution {
     5 public:
     6     bool canJump(int A[], int n) {
     7         if(n==1)  return true;
     8         else
     9         {
    10             for(int i=n-2;i>=0;i--)
    11             {
    12                 if(A[i]+i>=n-1)
    13                 {
    14                     return canJump(A,i+1);
    15                 }
    16             }
    17             return false;
    18         }
    19     }
    20 };
  • 相关阅读:
    匿名变量
    Vue父子组件传值与非父子传值
    TCP三次握手分析
    @media screen 响应式布局
    H5新增多媒体标签
    npm+node+vue配置一套带走
    vue+echarts全国疫情地图
    js本地时间格式化
    vue iview分页
    Vue打包后访问静态资源路径问题
  • 原文地址:https://www.cnblogs.com/sqxw/p/3980061.html
Copyright © 2020-2023  润新知