【LeetCode】55. 跳跃游戏

在这里插入图片描述

解法 1

从左到右遍历数组,假设当 index = x1 时,nums[x1] = 0,则继续向右遍历,直接遇到不为 0 的元素,假设此时 index = x2

且在遍历的时候,记录 index 在 x1 之前的元素,有 maxIndex = index+nums[index](maxIndex 表示下标为 index 对应的元素值所能跨到最远位置)。

如果 maxIndex < x2,则表示从 x1 之前的任一元素位置跳跃,都无法跨过 x2 位置时的 0,因此返回 false。

但是要记住一种特殊情况,假设 maxIndex >= nums.length - 1,则表示已经跳跃到末尾了,此时可以直接返回 true。

public boolean canJump(int[] nums) {
    if (nums == null || nums.length == 0) {
        return false;
    }
    int len = nums.length;
    // 注意 nums[0] 为 0 的特殊情况
    if (nums[0] == 0) {
        return len == 1;
    }
    
    int index = 0;
    int lastMax = 0;
    while (index < len) {
        if (nums[index] == 0) {
            ++index;
            // 防止越界
            while (index < len && nums[index] == 0) {
                ++index;
            }
            if (lastMax < index) {
                return false;
            }
        } else {
            if (index + nums[index] > lastMax) {
                lastMax = index + nums[index];
                if (lastMax >= len - 1) {
                    return true;
                }
            }
            ++index;
        }
    }
    return true;
}
解法 2

引用自该题目前为止通过的最快解法。

从右到左返回来遍历。

如果有 index = y1,假定 y1 对应的位置能够跳跃到末尾,则只要在 index < y1 的元素中,找到能够跳跃到 y1 位置,或者超越 y1 位置的元素即可。

如果最后能够逆着来到起始位置,则表示成立。

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

上述即贪心算法的实现,具体可以参考 官方解析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值