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.

For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

Logic

Update for loop's end point until it reaches array's end or finishes ahead.

Time Complexity

O(n)

Space Complexity

O(1)

Code

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

顾明轩
1 声望0 粉丝