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     }
  • 相关阅读:
    SQL CREATE INDEX 语句:如何创建索引?
    SQL DEFAULT 约束:使用方法及撤销方法解析
    SQL CHECK 约束:使用方法及撤销方法剖析
    SQL FOREIGN KEY 约束:外键的用法大全
    oracle表的管理和单行函数、多行函数、行列转换、分析函数以及集合运算
    oracle插入数据中文乱码问题
    oracle体系结构
    PL/SQL连接Oracle数据库
    SVN规范
    IDEA下 SVN 配置与使用
  • 原文地址:https://www.cnblogs.com/feiling/p/3241934.html
Copyright © 2011-2022 走看看