Jump Game I II

Jump I

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.

 

ref  http://blog.csdn.net/linhuanmars/article/details/21354751

public class Solution {
    public boolean canJump(int[] A) {
        if(A==null || A.length<1) return false;
        // http://blog.csdn.net/linhuanmars/article/details/21354751 DP 作法。我觉得自己掌握的还是不行
        int reach=0;
        for(int i= 0; i< A.length && i<=reach; i++){
       if (reach>=A.length-1) return true; //加了这个小判断后,速度大幅度提升 100ms左右 reach
= Math.max(reach, A[i]+i); } return reach>=A.length-1; } }

II 

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

http://blog.csdn.net/linhuanmars/article/details/21356187

public class Solution {
    public int jump(int[] A) {
        if(A==null || A.length==0) return 0;
        int reach=0, lastreach=0, step=0;
        for(int i=0; i<=reach && i<A.length;i++){
            if(lastreach==A.length-1) return step;
            if(i>lastreach){
                step++;
                lastreach=reach;
            }
            
            reach = Math.max(reach, A[i]+i);
            
        }
        return step;
    }
}

 

posted @ 2015-04-14 10:28  世界到处都是小星星  阅读(137)  评论(0编辑  收藏  举报