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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章