[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]为从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.

 

[Leetcode]-- Jump Game
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;
        
    }
}
[Leetcode]-- Jump Game

思路2:

Greedy

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

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

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

[Leetcode]-- Jump Game
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;
        
    }
}
[Leetcode]-- Jump Game

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

       水中的鱼

[Leetcode]-- Jump Game

上一篇:mysql 随机查询 效率比较


下一篇:数据从mmsql导入mysql