Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: [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: [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.
题目链接:https://leetcode.com/problems/jump-game/
题目分析:不断更新当前所能到达的最远距离,若当此距离小于当前下标,则说明到不了当前位置
3ms,时间击败100%
class Solution {
public boolean canJump(int[] nums) {
for (int i = 0, cur = 0; i < nums.length; i++) {
if (cur < i) {
return false;
}
cur = Math.max(cur, i + nums[i]);
}
return true;
}
}

本文深入解析了LeetCode上的一道经典算法题——跳跃游戏。通过一个直观的例子,阐述了如何判断能否从数组的起始位置到达最后一个元素的方法。文章详细解释了一种高效算法,通过不断更新所能达到的最远距离,判断是否能够成功到达终点。最后,提供了一个简洁的Java代码实现,该实现仅需3ms,时间效率高达100%。
413

被折叠的 条评论
为什么被折叠?



