原题连接:https://leetcode-cn.com/problems/jump-game-ii/
解题思路:
- 该题是55. 跳跃游戏的加强版。
- 由于该题保证最终能够到达
nums.length - 1
位置,我们只要考虑每次都跳跃到当前已知能够到达的最远位置即可。 - 例如输入
[2,3,1,1,4]
,第一次从索引0跳到索引2,此时target = 2
,同时遍历数组。 - 当遍历到
target
为2时,我们已遍历的数组部分为[2,3,1]
,那么第二次跳跃就能跳到索引4,即target = 4
。事实上此时已经跳跃到了最后位置,继续遍历对结果其实已无影响。 - 注意我们实际上是先跳跃,再遍历的过程。而如果遍历到最后位置,可能会触发一次多余的跳跃,因此我们需要在
i = nums.length - 2
时提前退出循环。
/**
* @param {number[]} nums
* @return {number}
*/
var jump = function (nums) {
let max = 0; // 当前已遍历的坐标可以达到的最大位置
let target = 0; // 存储当前自己所在的位置,即起跳的位置
let step = 0; // 跳跃的次数
// 无需遍历到nums.length - 1,因为target在遍历到nums.length - 1之前就已经>=nums.length - 1
for (let i = 0; i < nums.length - 1; i++) {
// 获取当前已知可到达的最大距离
max = Math.max(max, i + nums[i]);
if (i === target) {
// 当遍历到当前位置时,跳到当前已知的最远位置
target = max;
// 记录跳跃次数
step++;
}
}
return step;
};