【LeetCode】 55. Jump Game 跳跃游戏(Medium)(JAVA)

【LeetCode】 55. Jump Game 跳跃游戏(Medium)(JAVA)

题目地址: https://leetcode.com/problems/jump-game/

题目描述:

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.

题目大意

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

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

判断你是否能够到达最后一个位置。

解题方法

1、记录下当前可以跳的最远距离的最大值
2、如果当前 index 比最远距离大,说明已经无法往前跳了

class Solution {
    public boolean canJump(int[] nums) {
        if (nums.length <= 1) return true;
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (i > max) return false;
            if ((i + nums[i]) > max) max = i + nums[i];
            if (max >= (nums.length - 1)) return true;
        }
        return true;
    }
}

执行用时 : 2 ms, 在所有 Java 提交中击败了 63.60% 的用户
内存消耗 : 40.9 MB, 在所有 Java 提交中击败了 24.76% 的用户

扫描二维码关注公众号,回复: 9882189 查看本文章
发布了81 篇原创文章 · 获赞 6 · 访问量 2289

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104778043