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], return true.

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

    [解题思路]

    1.一维DP,jump[i]表示到达位置i剩余的最大步数

     1 public boolean canJump(int[] A) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         int len = A.length;
     5         //using DP
     6         int[] jump = new int[len];
     7         jump[0] = 0;
     8         
     9         for(int i = 1; i < len; i++){
    10             jump[i] = Math.max(jump[i - 1], A[i - 1]) - 1;
    11             if(jump[i] < 0){
    12                 return false;
    13             }
    14         }
    15         return true;
    16     }

     2.二维DP

    f(i)表示是否可以从position 0到达i

    f(i) = OR 'f(j) && A[j] + j >= i' j = 0,...,i - 1

    时间复杂为O(N^2), 大数据集会超时

     1 public boolean canJump(int[] A) {
     2         if(A.length == 0){
     3             return true;
     4         }
     5         int len = A.length;
     6         boolean[] f = new boolean[len];
     7         f[0] = true;
     8         for(int i = 1; i < len; i++){
     9             for(int j = 0; j < i; j++){
    10                 f[i] = f[i] || (f[j] && (A[j] + j >= i));
    11             }
    12         }
    13         return f[len - 1];
    14     }

     3.Greedy

    维护一个maxDis变量,表示当前可以到达的最大距离

    当maxDis >= len - 1表示可以到达

    每经过一点都将maxDis 与 i + A[i]进行比较,更新最大值

     1 public boolean canJump(int[] A) {
     2         if(A.length == 0){
     3             return true;
     4         }
     5         int len = A.length;
     6         int maxDis = 0;
     7         for(int i = 0; i < len; i++){
     8             
     9             if(maxDis < i){
    10                 return false;
    11             }
    12             maxDis = Math.max(maxDis, i + A[i]);
    13             if(maxDis >= len - 1){
    14                 return true;
    15             }
    16         }
    17         
    18         return false;
    19     }
  • 相关阅读:
    利用idea里面的mysql插件进行导入sql文件
    JSTL标签
    deepin20系统下配置JAVA开发环境
    deepin20安装及问题解决
    SpringBoot 在项目启之后执行自定义方法的两种方式
    Nick 的经验书
    Java 经验书
    SpringBoot 经验书
    Linux 经验书
    在MacOS中启动SSH服务
  • 原文地址:https://www.cnblogs.com/feiling/p/3241934.html
Copyright © 2011-2022 走看看