首页 > 其他 > 详细

LeetCode-45 Jump Game II

时间:2015-03-13 22:11:49      阅读:288      评论:0      收藏:0      [点我收藏+]

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.)

 

思路:

min 表示到达第i个节点需要jump的最小数目;

maxReach 表示经过min次跳跃后最远可以达到的位置;

maxCanReach表示在遍历过的节点中,最远可以到达的位置(即A[i]+i);

当i>maxReach,说明经过min次跳跃已经不足以到达第i个节点,需要多跳一次;而经过min+1次跳跃之后,最远能到达的位置manReach = maxCanReach;

如果maxReach >=A.length-1,说明至少经过min次跳跃即可达到终点。

代码如下:

public int jump(int[] A) {
        if(A == null || A.length < 2)
            return 0;
        if(A[0] == 0)
            return 0;
        if(A[0] >= A.length-1)
            return 1;
        
        int min = 1;//min jump
        int maxReach = A[0]; 
        int maxCanReach = A[0];
        for(int i=1; i<A.length; i++) {
            if(i > maxReach) {
                min++;
                maxReach = maxCanReach;
            }
            if(maxReach >= A.length-1) {
                return min;
            }
            if(A[i] + i > maxCanReach)
                maxCanReach = A[i] + i;
            
        }
        return min;
    }

 

LeetCode-45 Jump Game II

原文:http://www.cnblogs.com/linxiong/p/4336046.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!