Jump Game —— LeetCode

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.

题目大意:给定一个非负数组,每个元素代表可以跳的步数,判断从第一个能否跳到最后一个。

解题思路:暴力?二重循环,检查是否能到达最后一个元素。

     优化:时间O(n),空间O(1),一次遍历,首先记录当前可以覆盖的最大下标,遍历的时候如果从当前位置可以跳的更远则更新最大下标,如果当前位置不在最大下标覆盖范围内则return false,如果最大下标比数组更长,则return true。

public class Solution {
    public boolean canJump(int[] nums) {
        if(nums == null){
            return false;
        }
        int pos = 0;
        for(int i=0;i<nums.length;i++){
            if(pos>=nums.length-1){
                return true;
            }
            if(i<=pos){
                if(i+nums[i]>pos)
                    pos= i +nums[i];    
            }
            else{
                return false;
            }
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/aboutblank/p/4514119.html