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     }
  • 相关阅读:
    Session的使用与管理
    CSS控制文字,超出部分显示省略号
    MP4 文件前端获取视频封面
    prefetch预加载功能使用
    react-学习之路-react-router-解决问题记录
    如何将一个div盒子水平垂直都居中?
    window下查看端口号,并删除对应进程
    判断js 验证字符串里面有没有包含汉字:
    vue 现有的$变量 以及如何添加全局变量
    与人言
  • 原文地址:https://www.cnblogs.com/feiling/p/3241934.html
Copyright © 2011-2022 走看看