数组跳跃问题

2024-03-11  本文已影响0人  Cherry丶小丸子
// 数组跳跃问题:
// 有一个整数数组 nums,数组中元素表示你在该位置的最大跳跃长度
// 如果你能到达最后一个索引,则返回 true, 否则返回 false

// 实例一
// 输入:nums = [2, 3, 1, 1, 4]
// 输入:true
// 解释:从索引 0 跳到索引 1 需要跳 1 步,然后在跳 3 步到最后一个索引

// 实例二
// 输入:nums = [3, 2, 1, 0, 4]
// 输出: false
// 解释:无论你怎么跳,你都会到达索引 3,他的最大跳跃长度是 0,这使得到达最后一个索引变得不可能
function canJump(nums){
    // 定义一个变量记录最远可以到达的位置
    let maxReach = 0;
    for(let i = 0; i < nums.length; i++){
         // 判断当前位置是否可以到达
        if(i > maxReach) return false;
        // 检查最大的可达位置
        maxReach = Math.max(maxReach, i + nums[i]);
    }
    return true;
}
console.log(canJump([2, 3, 1, 1, 4]))   
// 数组的跳跃问题
// 有一个整数数组 nums,数组中元素表示你在该位置的最大跳跃长度
// 数组一定可以到达最后一个元素,返回到达最后元素的最下跳跃次数

// 实例:
// 参数:nums = [2, 3, 1, 1, 4]
// 返回:2
function jump(nums){
    let jumps = 0;
    let currentFarthest = 0;
    let currentEnd = 0;

    for(let i = 0; i < nums.length - 1; i++){
        currentFarthest = Math.max(currentFarthest, nums[i] + i);
        if(i === currentEnd){
            jumps++
            currentEnd = currentFarthest
        }
    }
    return jumps;
}
console.log(jump([2, 3, 1, 1, 4]))
上一篇 下一篇

猜你喜欢

热点阅读