[LeetCode] 55. Jump Game jump game (Medium) (JAVA)

[LeetCode] 55. Jump Game jump game (Medium) (JAVA)

Topic Address: https://leetcode.com/problems/jump-game/

Subject description:

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.

Subject to the effect

Given a non-negative integer array, you initially located in the first position of the array.

Each element in the array represents the maximum length you can jump in that position.

To determine whether you are able to reach a final position.

Problem-solving approach

1, the current record can jump the farthest distance of maximum
2, if the current index is greater than the maximum distance, the description has been unable to jump ahead

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;
    }
}

When execution: 2 ms, beat the 63.60% of all users to submit in Java
memory consumption: 40.9 MB, defeated 24.76% of all users to submit in Java

Published 81 original articles · won praise 6 · views 2289

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/104778043
Recommended