给定一个长度为 n 的 0 索引整数数组 nums。初始位置在下标 0。
每个元素 nums[i] 表示从索引 i 向后跳转的最大长度。换句话说,如果你在索引 i 处,你可以跳转到任意 (i + j) 处:
0 <= j <= nums[i]且i + j < n
返回到达 n - 1 的最小跳跃次数。测试用例保证可以到达 n - 1
贪心算法
我们可以维护一个当前跳跃步数能达到的最远范围
举例说明:nums = [2, 3, 1, 1, 4]
- 初始状态:
ans=0,cur_end=0,max_pos=0。 - i = 0:
max_pos = max(0, 0+2) = 2。到达cur_end,ans变为 1,cur_end更新为 2。 - i = 1:
max_pos = max(2, 1+3) = 4。 - i = 2:
max_pos = max(4, 2+1) = 4。到达cur_end,ans变为 2,cur_end更新为 4。 - 此时
cur_end已到达数组末尾,循环结束。返回结果2。
/**
* @param {number[]} nums
* @return {number}
*/
var jump = function(nums) {
let ans = 0
let cur_end = 0
let max_pos = 0
for(let i=0;i<nums.length-1;i++){
max_pos = Math.max(max_pos,i+nums[i])
if(i === cur_end){
ans++
cur_end = max_pos
}
}
return ans
};