Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://leetcode.com/problems/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.)

解题思路:

借鉴上一题的思路,这里当i能到的点已经超过maxReach的时候,就去更新maxReach,同时也更新从i+1到maxReach(或者A.length - 1,因为可能已经超出了)的所有点的步数。

public class Solution {
    public int jump(int[] A) {
        int maxReach = 0;
        int[] minStep = new int[A.length];
        for(int i = 0; i < A.length; i++){
            if(i + A[i] > maxReach){
                maxReach = i + A[i];
                for(int j = i + 1; j <= Math.min(maxReach, A.length - 1); j++){
                    if(minStep[j] == 0){
                        minStep[j] = minStep[i] + 1;
                    }else{
                        minStep[j] = Math.min(minStep[j], minStep[i] + 1);
                    }
                }
            }
        }
        return minStep[A.length - 1];
    }
}

因为从i+1到之前的maxReach + 1中的step,肯定是之前的大。比如13711111111。7后的2个1,和后面的更多的1。因为现在又比之前多了一步,所以代码可以改成如下。

public class Solution {
    public int jump(int[] A) {
        int maxReach = 0;
        int[] minStep = new int[A.length];
        for(int i = 0; i < A.length; i++){
            if(i + A[i] > maxReach){
                for(int j = maxReach + 1; j <= Math.min(i + A[i], A.length - 1); j++){
                        minStep[j] = minStep[i] + 1;
                }
                maxReach = i + A[i];
            }
        }
        return minStep[A.length - 1];
    }
}

 大神code ganker分享了更好的解法,http://blog.csdn.net/linhuanmars/article/details/21356187。思想其实和上面也一样,比如3后面的7,即使更新了maxReach,但是从3到7后的两个1,step都不要增加的,因为3就可以到。直到7后的第三个1,才需要step++。同时要把lastMaxReach更新为最新的maxReach。

一样的思想,但是却省去了内部的循环。

public class Solution {
    public int jump(int[] A) {
        int maxReach = 0, step = 0, lastMaxReach = 0;
        for(int i = 0; i < A.length && i <= maxReach; i++){
            if(i > lastMaxReach){
                lastMaxReach = maxReach;
                step++;
            }
            if(i + A[i] > maxReach){
                maxReach = i + A[i];
            }
        }
        return step;
    }
}

 

posted on 2015-03-23 22:03  NickyYe  阅读(168)  评论(0编辑  收藏  举报