26 lines
1.1 KiB
JavaScript
26 lines
1.1 KiB
JavaScript
/**
|
||
* https://leetcode.cn/problems/jump-game/?envType=study-plan-v2&envId=top-interview-150
|
||
* @param {number[]} nums
|
||
* @return {boolean}
|
||
*/
|
||
const canJump = function (nums) {
|
||
|
||
};
|
||
|
||
/*
|
||
贪心算法,每一次计数自己能走的最长距离,如果在某一个位置上计算出自己的最长距离超过了数组的最大下标,则表明可以跳跃整个数组
|
||
如果遍历完数组还是没有找到,则表明不能跳跃数组
|
||
*/
|
||
function f1(nums) {
|
||
let farthest = 0; // 默认能走到的最远下标,初始的时候能走到数组的第一个下表0
|
||
for (let i = 0; i < nums.length; i++) {
|
||
// 如果能走的最远距离连当前下表都无法走到直接放回false
|
||
if (farthest < i) return false;
|
||
// 如果能走到当前下标,就比较farthest 和 当前下表加上此时的值谁大,更新farthest
|
||
farthest = Math.max(farthest, i + nums[i]);
|
||
// 如果更新后的farthest 超过了数组的最大下表,就表示数组能跳跃整个数组,直接返回true
|
||
if (farthest >= (nums.length - 1)) return true;
|
||
}
|
||
return false;
|
||
}
|