Given an array of non-negative integers, you are initially positioned at the first index of the array.html
Each element in the array represents your maximum jump length at that position.java
Your goal is to reach the last index in the minimum number of jumps.git
Example:github
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,代碼以下:oop
解法一:post
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; } };
還有一種寫法,跟上面那解法略有不一樣,可是本質的思想仍是同樣的,關於此解法的詳細分析可參見網友 實驗室小紙貼校外版的博客,這裏 cur 是當前能到達的最遠位置,last 是上一步能到達的最遠位置,遍歷數組,首先用 i + nums[i] 更新 cur,這個在上面解法中講過了,而後判斷若是當前位置到達了 last,即上一步能到達的最遠位置,說明須要再跳一次了,將 last 賦值爲 cur,而且步數 res 自增1,這裏小優化一下,判斷若是 cur 到達末尾了,直接 break 掉便可,代碼以下:優化
解法二:this
class Solution { public: int jump(vector<int>& nums) { int res = 0, n = nums.size(), last = 0, cur = 0; for (int i = 0; i < n - 1; ++i) { cur = max(cur, i + nums[i]); if (i == last) { last = cur; ++res; if (cur >= n - 1) break; } } return res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/45
相似題目:
參考資料:
https://leetcode.com/problems/jump-game-ii/
https://leetcode.com/problems/jump-game-ii/discuss/18028/O(n)-BFS-solution
https://leetcode.com/problems/jump-game-ii/discuss/18023/Single-loop-simple-java-solution