LeetCode刷題筆記(貪心):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 is2. (Jump1step from index 0 to 1, then3steps to the last index.)

給定一個非負整數數組,最初定位在數組的第一個索引處。 數組中的每個元素表示您在該位置的最大跳躍長度。 你的目標是達到最小跳躍次數的最後一個索引。 例如:給定數組A = [2,3,1,1,4]到達最後一個索引的最小跳轉次數是2。 (從索引0跳到1,然後3步到最後一個索引。)

解題思路

只要能夠到達的最遠距離還沒有到n,就必須再走下一步。所以只需要在上一道題程序的基礎上,加入計數,並且更新最後一個跳點即可。

C++版代碼實現

class Solution {
public:
    int jump(int A[], int n) {
        if(A == NULL || n == 0)
            return false;
        //maxReach標記能跳到的最遠處。
        int maxReach = 0, curReach = 0, steps = 0;
        //maxReach >= i表示此時能跳到i處,0 <= i < n表示掃描所有能到達的點,並計算能達到的最遠距離。
        for(int i = 0; i < n && i <= maxReach; ++i) {
            if(i > curReach){
                ++steps;
                curReach = maxReach;
            }
            maxReach = max(maxReach, A[i] + i);
        }
        //如果最後跳的最遠的結果大於等於n-1,那就能跳到最後。
        return maxReach < n - 1 ? false : steps;
    }
};

系列教程持續發佈中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章