题目:
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.)
代码:
class Solution {public: int jump(vector & nums) { int max_jump=0, next_max_jump=0, min_step=0; for ( int i = 0; i<=max_jump; ++i ) { if ( max_jump>=nums.size()-1 ) break; if ( max_jump < i+nums[i] ) next_max_jump = std::max(next_max_jump, i+nums[i]); if ( i==max_jump ) { max_jump = next_max_jump; min_step++; } } return min_step; }};
tips:
参考的Greedy思路。
这道题要求求出所有可能到达路径中的最短步长,为了保持O(n)的解法继续用Greedy。
这道题的核心在于贪心维护两个变量:
max_jump:记录上一次跳跃能跳到最大的下标位置
next_max_jump:记录遍历所有max_jump之前的元素后,下一次可能跳到的最大下标位置
举例说明如下:
原始数组如右边所示:{7,0,9,6,9,6,1,7,9,0,1,2,9,0,3}
初始:max_jump=0 next_max_jump=0 min_step=1
i=0:next_max_jump=7 更新max_jump=7 更新min_step=1
i=1: 各个值不变
i=2: i+nums[i]=2+9=11>7 更新next_max_jump=11
i=3:i+nums[i]=3+6=9<11 不做更新
i=4: i+nums[i]=4+9=13>11 更新max_jump=13
...
i=7:i+nums[i]=7+7=14 >= nums.size()-1 返回min_step=2
完毕
==========================================
第二次过这道题,不太顺,大体复习了下思路。
class Solution {public: int jump(vector & nums) { if ( nums.size()==0 ) return 0; int ret = 0; int nextJump = 0; int maxLength = 0; for ( int i=0; i<=maxLength; ++i ) { if ( maxLength>=nums.size()-1 ) break; nextJump = std::max(i+nums[i], nextJump); if ( i==maxLength ) { maxLength = nextJump; ret++; } } return ret; }};
==========================================
第三次过这道题,把代码改了一行,但是整体结构清晰了不少。
class Solution {public: int jump(vector & nums) { if (nums.size()<2) return 0; int steps = 0; int local = 0; int next = local; for ( int i=0; i<=local; ++i ) { next = max(next, i+nums[i]); if ( i==local ) { steps++; local = next; if ( local>=nums.size()-1 ) return steps; } } return 0; }};
next只负责看下一跳能够到哪。
什么时候更新local了,再判断能否跳到尾部。