xianzao / xianzao-interview

前端 每日一道面试题
64 stars 4 forks source link

【2022.12.16】跳跃游戏 #20

Open xianzao opened 1 year ago

xianzao commented 1 year ago

给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标。

示例 1:

输入:nums = [2,3,1,1,4] 输出:true 解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。

示例 2:

输入:nums = [3,2,1,0,4] 输出:false 解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。

提示:

xianzao commented 1 year ago
/**
 * @param {number[]} nums
 * @return {boolean}
 */
var canJump = function(nums) {
    if (!nums) return false;

    let last = nums.length - 1;
    for(let i = last - 1; i >= 0; i--) {
        if (nums[i] + i >= last) {
            last = i
        }
    }
    return last === 0;
};
Pharaoh-Li commented 1 year ago
/**
 * @param {number[]} array
 * @return {boolean}
 */
const jumpGame = (array) => {
    if (!array) return false
    let index = 0
    let value = array[index]
    let n = 0
    while(index < array.length - 1 && value !== 0) {
        n ++
        index += value
        value = array[index]
    }
    console.log(n);
    if (index === array.length - 1) {
        return true
    }
    return false
}