[leetcode] 55.Jump Game

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;
    }
}
阅读 978

推荐阅读
pawn
用户专栏

算法,前端起步,记录学习过程

0 人关注
4 篇文章
专栏主页