Come from : [https://leetcode-cn.com/problems/jump-game-ii/]
45. Jump Game II
1.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.
2.Answer
hard 类型题目(第一次 解决hard 类型 题目啊,好激动,好紧张)。贪心算法。
算法分析:
AC代码如下:
class Solution {
public:
int jump(vector<int>& nums) {
int len = nums.size();
if(len < 2) //数组长度小于2,说明不用跳
{
return 0;
}
int jump_min = 1; //能进行到这说明 至少跳一次
int current_max_index = nums[0]; //当前可以达到的最远位置
int pre_max_index = nums[0]; //在遍历过程中,可以达到的最远位置
for(int i = 1; i < len ; ++i)
{
if( i > current_max_index ) //无法向前移动了,才进行跳跃(贪心思想算法)
{
++jump_min;
current_max_index = pre_max_index; //更新当前可以到达的最远位置
}
if(pre_max_index < nums[i] + i)
{
pre_max_index = nums[i] + i;//更新premax_max_index,即最远位置;
}
}
return jump_min;
}
};
3.大神的算法
大神AC速度第一代码:
class Solution {
public:
int jump(vector<int>& nums) {
int step = 0;
for (int i = 0, j = 0, k = 0; i < nums.size() - 1; i++) {
j = max(i + nums[i], j);
if (i >= k) {
k = j;
step++;
}
}
return step;
}
};
4.我的收获
贪心算法进阶啦。。。
fighting。。。
2019/6/12 胡云层 于南京 100