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.
题目解析:
题目翻译下:
/**
* 给出一个非负整数数组,你最初在数组第一个元素的位置
* 数组中的元素代表你在这个位置可以跳跃的最大长度
* 你的目标是用最少的跳跃次数来到达数组的最后一个元素的位置
* 例如
* 给出数组 A =[2,3,1,1,4]
* 最少需要两次才能跳跃到数组最后一个元素的位置。
*(从数组下标为 0的位置跳长度1到达下标1的位置,然后跳长度3到数组最后一个元素的位置)
*/
有了上述翻译,应该大家秒懂了吧!不在赘述题目意思啦!
代码思路解析:
借鉴了博客的的图,供大家参考,遍历至i=4的时候,图解有错误,cur = 8,(即当前位置值是4,可以往后跳4步),我这边懒得重新画图啦,贴上链接,尊重其他人劳动成果。具体理解请以我代码为主,代码中有详细注释,谢谢!
https://www.cnblogs.com/lichen782/p/leetcode_Jump_Game_II.html
代码:
class Solution {
public:
int jump(vector<int>& nums) {
//[2,3,1,1,4]
if(nums.size() == 0)
{
return 0;
}
int steps = 0;//步数
int curStep = 0;//前一下标能达到的位置
int maxStep = 0;//当前下标能达到的位置
for(int i = 0;i < nums.size();i++)
{
//i = 0;false
//i = 1;true
//i = 2;false
//i = 3;true curStep = 2
//i = 4;true
if(i > curStep)
{
steps++;//i = 1,steps + 1 = 1;i = 3,steps + 1 = 2
curStep = maxStep;//下标0,能达到的位置,记录下来,curStep = 2;下标3,能达到的位置,记录下来,curStep = 4;
}
//i = 0;max(0,2) = 2;最远能到下标为2的位置,即nums[2] = 1;
//i = 1;max(2,4) = 4;最远能到下标为4的位置,即nums[4] = 4;这是最远的位置
//i = 2;max(4,3) = 4;不更新
//i = 3;max(4,4) = 4;不更新
//i = 4;max(4,8) = 8;maxStep = 8
maxStep = max(maxStep,nums[i] +i);
}
return steps;//2
}
};
性能:
总结:
1.借用二个变量是必要的,分别记录当前下标达到的最远距离,以及记录前一下标达到的最远距离,目的可以得出最佳步数,如例从数组下标为 0的位置跳长度1到达下标1的位置,然后跳长度3到数组最后一个元素的位置,下标为0位置上值是2,即可跳2步,而跳一步后,即可达到最后位置,所以必须分别有二个变量记录是必要的。