题目
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
思路
如果移动下标达到了当前这一步的最大覆盖最远距离了,还没有到终点的话,那么就必须再走一步来增加覆盖范围,直到覆盖范围覆盖了终点。
const permute = (nums = [2,3,1,1,4]) => {
if(nums.length === 1) return 0
let curDistance = 0 //最远距离下标
let steps = 0 //跳跃次数
let nextDistance = 0 //下一步最远距离下标
for(let i = 0; i < nums.length - 1; i++) {
nextDistance = Math.max(nums[i] + i, nextDistance)
if(i === curDistance) {
steps++
curDistance = nextDistance
if(curDistance >= nums.length - 1) {
break
}
}
}
return steps
}