45. Jump Game II 跳躍游戲二

題目鏈接
tag:

  • Hard;
  • Greedy;

question:
??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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

Note:
You can assume that you can always reach the last index.

思路:
??這題是之前那道Jump Game 跳躍游戲 的延伸,那題是問能不能到達最后一個數字,而此題只讓我們求到達最后一個位置的最少跳躍數,貌似是默認一定能到達最后位置的? 此題的核心方法是利用貪婪算法Greedy的思想來解,想想為什么呢? 為了較快的跳到末尾,我們想知道每一步能跳的范圍,這里貪婪并不是要在能跳的范圍中選跳力最遠的那個位置,因為這樣選下來不一定是最優解,這么一說感覺又有點不像貪婪算法了。我們這里貪的是一個能到達的最遠范圍,我們遍歷當前跳躍能到的所有位置,然后根據該位置上的跳力來預測下一步能跳到的最遠距離,貪出一個最遠的范圍,一旦當這個范圍到達末尾時,當前所用的步數一定是最小步數。我們需要兩個變量cur和pre分別來保存當前的能到達的最遠位置和之前能到達的最遠位置,只要cur未達到最后一個位置則循環繼續,pre先賦值為cur的值,表示上一次循環后能到達的最遠位置,如果當前位置i小于等于pre,說明還是在上一跳能到達的范圍內,我們根據當前位置加跳力來更新cur,更新cur的方法是比較當前的cur和i + A[i]之中的較大值,如果題目中未說明是否能到達末尾,我們還可以判斷此時pre和cur是否相等,如果相等說明cur沒有更新,即無法到達末尾位置,返回-1,代碼如下:

class Solution {
public:
    int jump(vector<int>& nums) {
        int res = 0, n = nums.size(), i = 0, cur = 0;
        while (cur < n - 1) {
            ++res;
            int pre = cur;
            for (; i<= pre; ++i)
                cur = max(cur, i + nums[i]);
            if (pre == cur) return -1; // May not need this
        }
        return res;
    }
};
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容