Jump Game II
A.题意
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 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.
B.思路
这道题目其实跟之前做过的jump game类似了,只是这次要你求出跳跃步数,这里好像每一次都能到达终点,这里我们还是使用贪心算法,每次我们用一个curFathest记录当前能到达区间里面能再次跳到的最远端,用curEnd记录你当前的跳跃区间,当到达curEnd时我们选择该区间里面能跳到的最远的curFathest作为下一个curEnd即可
C.代码实现
class Solution {
public:
int jump(vector<int>& nums) {
int jumps = 0, curEnd = 0, curFarthest = 0;
for (int i = 0;i < nums.size() - 1;i++)
{
curFarthest = max(curFarthest,nums[i] + i);
if (i == curEnd)
{
jumps++;
curEnd = curFarthest;
if (curEnd >= nums.size() - 1)
{
break;
}
}
}
return jumps;
}
};