LeetCode.55 Jump Game

来源:互联网 发布:java try的用法 编辑:程序博客网 时间:2024/06/05 05:40

题目:

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.

分析(原创):

class Solution {    public boolean canJump(int[] nums) {        //给定非负数的数组,每个元素表示你可以走的最大步数(意味着你可以选择更小的或者),判断是否可以走到最末尾        //思路:先求出当前节点之前能到的最大值,与当前节点下标比较,若小于,说明根本无法到达该节点        //直接返回false。若到达该节点,且该节点能到达的最大范围超过或者等于num的长度,则直接返回true。                if(nums.length==0||nums==null) return true;                //创建preSum数组表示当前节点能到达的最大范围        int [] preSum=new int[nums.length];        int max=0;        for(int i=0;i<nums.length;i++){            if(max<i){                //说明无法到达该节点                return false;            }                        preSum[i]=i+nums[i];            if(preSum[i]+1>=nums.length){                //可以直接到达最后                return true;            }            max=Math.max(max,preSum[i]);        }                return true;    }}

分析(参考答案):

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