55. Jump Game
55. Jump Game
题目
You are given an integer array nums
. You are initially positioned at the array's first index , and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, orfalse
otherwise.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 10^4
0 <= nums[i] <= 10^5
题目大意
给你一个非负整数数组 nums
,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标,如果可以,返回 true
;否则,返回 false
。
示例 1:
输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
示例 2:
输入:nums = [3,2,1,0,4]
输出:false
解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
解题思路
这道题表面上不是求最值,但是可以改一改:
请问通过题目中的跳跃规则,最多能跳多远?如果能够越过最后一格,返回 true
,否则返回 false
。
所以解题关键在于求出能够跳到的最远距离。
代码
/**
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function (nums) {
const n = nums.length;
let max = 0;
for (let i = 0; i < n - 1; i++) {
// 不断计算能跳到的最远距离
max = Math.max(max, i + nums[i]);
// 可能碰到了 0,卡住跳不动了
if (max <= i) {
return false;
}
}
return max >= n - 1;
};
相关题目
- [45. 跳跃游戏 II](https://leetcode.com/problems/jump-game-ii)
- [1306. 跳跃游戏 III](https://leetcode.com/problems/jump-game-iii)
- [1871. 跳跃游戏 VII](https://leetcode.com/problems/jump-game-vii)
- [🔒 Jump Game VIII](https://leetcode.com/problems/jump-game-viii)
- [2617. 网格图中最少访问的格子数](https://leetcode.com/problems/minimum-number-of-visited-cells-in-a-grid)
- [2789. Largest Element in an Array after Merge Operations](https://leetcode.com/problems/largest-element-in-an-array-after-merge-operations)