LeetCode-55. Jump Game

来源:互联网 发布:杭州淘宝拍摄基地在哪 编辑:程序博客网 时间:2024/05/18 01:11

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.

思路和解题步骤类似于Maximum Subarray的思路三

思路:

  1. 定义一个变量来保存最远可以到达的位置。
  2. 每次循环时,我们得到当前到达的最远位置nums[i]+i,所以我们要在当前可以到达的最远位置和之前记录下的最远位置中选择,取较大值保存。如果此时能到达的最远位置已经不小于数组长度,则直接返回true。

细节

  1. 考虑到nums={0}的情况,所以需要事先单独判断。
  2. 注意循环发生的判断条件。

Java实现

class Solution {    public boolean canJump(int[] nums) {        if(nums.length==1)            return true;        int reach=0;        for(int i=0;i<nums.length&&i<=reach;++i)        {            reach=Math.max(nums[i]+i,reach);            if(reach>=nums.length-1)                return true;        }        return false;    }}
原创粉丝点击