【LeetCode】114.Jump Game II
阿新 • • 發佈:2018-11-01
題目描述(Hard)
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.
題目連結
https://leetcode.com/problems/jump-game-ii/description/
Example 1:
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.
演算法分析
貪心法,找到每一步所能到達的最遠距離。
方法一:每次在當前區域中,尋找一個當前步所覆蓋的最大區域;
方法二:尋找下一步的最遠距離,如果當前位置大於最遠距離,則進行跳到下一步的最遠距離。
提交程式碼(方法一):
class Solution { public: int jump(vector<int>& nums) { int step = 0; int left = 0; int right = 0; if (nums.size() == 1) return 0; while(left <= right) { ++ step; int old_right = right; for (int i = left; i <= old_right; ++i) { int new_right = i + nums[i]; if (new_right >= nums.size() - 1) return step; if (new_right > right) right = new_right; } left = old_right + 1; } return 0; } };
提交程式碼(方法二):
class Solution {
public:
int jump(vector<int>& nums) {
//步數,下一步到達的最遠距離,當前最遠距離
int step = 0, cur = 0, last = 0;
for (int i = 0; i < nums.size(); ++i) {
if (i > last)
{
last = cur;
++step;
}
cur = max(cur, i + nums[i]);
}
return step;
}
};