LeetCode ---- 55、跳跃游戏

题目链接

思路:

遍历一遍数组即可。

从每个位置往后跳,每次都选择跳最大的步数。

若当前所在位置    不包含在   之前所能跳到的最远的位置里面,则不能跳到最后,返回false。

若当前所在位置    包含在   之前所能跳到的最远的位置里面,

则查看是否需要更新最远位置,即 比较 最远位置  与  当前位置加上能跳的最大数  的大小。

    public boolean canJump(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return true;
        }
        int maxPos = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (i <= maxPos) {
                maxPos = Math.max(maxPos, nums[i] + i);
            } else {
                return false;
            }
        }
        return maxPos >= nums.length - 1;
    }

猜你喜欢

转载自blog.csdn.net/sinat_34679453/article/details/106630633