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


和Jump Game I 一样 也是greedy algorithm的题。下面分析一下题目

要用最少的Jump到达最远的距离,从第一点开始看,

base case, 如果只有一个元素,那不用走也能到,这个没什么好说的

首先,从第一点所能走的step覆盖的所有范围,最少步数都是1

那么走两步能到达的最远距离,就是1所覆盖下得范围中,能走到最远的格子然后依次类推,走三步能到的最远距离就是走两步能到的距离中能走最远的。


下面代码中, maxIndex记录的是在当前的步数下,能走到最远的步数所存放的index。

max存放的是能走到最远的距离,注意比较的时候是用 A[i]+i 而不是用 A[i]。

如果在step=0的时候已经到最后一个格子了,那就不需要再增加步数了直接break掉就可以。


public class Solution {
    public int jump(int[] A) {
        if(A==null||A.length<2){
            return 0;
        }
        int minStep = 1;
        int steps = A[0];
        int max = 0;
        int maxIndex = 0;
        for(int i=1;i<A.length;i++){
            steps--;
            if(A[i]+i>max){
                max = A[i] + i;
                maxIndex = i;
            }
            if(steps==0&&i!=A.length-1){
                steps = A[maxIndex]-(i-maxIndex);
                minStep++;
                max=0;
            }
        }
        return minStep;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章