zoukankan      html  css  js  c++  java
  • 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 public class Solution {
     2     public boolean canJump(int[] A) {
     3      if(A == null)
     4         return true;
     5     int max = 0;
     6     for( int i = 0; i < A.length; i++){
     7         if(max < i)
     8             return false;
     9         if(max >= A.length-1)
    10             return true;
    11         max = Math.max(max, i+A[i]);
    12     }
    13        return true;
    14     }
    15 }

    思路1:

    一维DP,定义 jump[i]为从index 0 走到第i步时,剩余的最大步数。

    那么转移方程可定义为

     jump[i] = max(jump[i-1], A[i-1]) -1   **i!=0  
             = 0                   **i==0  
    


    然后从左往右扫描,当jump[i]<0的时候,意味着不可能走到i步,所以return false; 如果走到最右端,那么return true.

    public class Solution {
        public boolean canJump(int[] A) {
            int len = A.length;
            
            int[] jump = new int[len];
            jump[0] = 0;
            for(int i = 1; i < len; i++){
                // 从index = 0 到 i 剩余的最大步数, -1是应为从 i-1到 i 需要走一步
                jump[i] = Math.max(jump[i-1], A[i-1])-1;
                if(jump[i] < 0){
                    return false;
                }
            }
            
            return true;
            
        }
    }

    思路2:

    Greedy

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

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

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

    public class Solution {
        public boolean canJump(int[] A) {
            int len = A.length;
            if(len == 0) return true;
            
            int maxD = 0;
            
            for(int i = 0; i<len; i++){
                if(maxD < i)
                    return false;
                
                maxD = Math.max(maxD, i+A[i]);
                
                if(maxD >= len-1){
                    return true;
                }
            }
            
            return false;
            
        }
    }

     参考 : http://www.cnblogs.com/feiling/p/3241934.html

           水中的鱼

  • 相关阅读:
    Git 分支开发规范
    小程序技术调研
    弹性布局
    vue 自定义指令的魅力
    记一次基于 mpvue 的小程序开发及上线实战
    mpvue学习笔记-之微信小程序数据请求封装
    微信小程序开发框架 Wepy 的使用
    Hbuilder 开发微信小程序的代码高亮
    luogu3807 【模板】 卢卡斯定理
    luogu1955 [NOI2015] 程序自动分析
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3539126.html
Copyright © 2011-2022 走看看