个人记录-LeetCode 55. Jump Game

来源:互联网 发布:java获取本机端口号 编辑:程序博客网 时间:2024/05/29 18:44

问题:
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.

代码示例:

主要思路是:
每跳一次,都计算出下一次跳跃,可达到的最大位置。
然后,判断下一次可达到的最大位置,是否可达到终点,是否大于等于下一次的起跳位置。

public class Solution {    public boolean canJump(int[] nums) {        //第一次跳跃,最远的位置,即0+num[0]        int nextEnd = nums[0];        //最远位置,大于等于最后一个位置,可直接结束        if (nextEnd >= nums.length - 1) {            return true;        }        //初始位置为0,为了有实际的前进,下一次跳跃的起始位置为1        int nextBegin = 1;        //保存下一次跳跃的最远位置        int curMax = -1;        while(nextEnd < nums.length - 1) {            for (int i = nextBegin; i <= nextEnd; ++i) {                //计算出从当前位置,可跳跃达到的最远位置                if (i + nums[i] > curMax) {                    curMax = i + nums[i];                    //最远位置,大于等于最后一个位置,可直接结束                    if (curMax >= nums.length - 1) {                        return true;                    }                }            }            //下一次预期的起跳位置,为本次最后一个位置的下一个            nextBegin = nextEnd + 1;            //下一次可达到的最远位置            nextEnd = curMax;            curMax = -1;            //下一次最远的位置,小于预期的起跳位置,即跳不动了,结束            if (nextEnd < nextBegin) {                break;            }        }        return false;    }}
0 0