题目:
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<int>& 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:
参考Jump Game的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
完毕