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     }
  • 相关阅读:
    ubuntu12.04 安装eclipse
    loj 1429(可相交的最小路径覆盖)
    loj 1406(状态压缩)
    mysql数据库表插入单条数据/批量插入数据
    window7安装MongoDB详细步骤
    django中的setting全局变量的导入
    django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)
    DjangoDRF序列化组件使用
    python并发编程知识点总结
    协程+IO切换实现并发
  • 原文地址:https://www.cnblogs.com/feiling/p/3241934.html
Copyright © 2011-2022 走看看