LeetCode-45 Jump Game 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.)

 

思路:

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;
    }

 

posted on 2015-03-13 21:23  linxiong1991  阅读(119)  评论(0编辑  收藏  举报

导航