leetcode 55. 跳跃游戏

@(labuladong的算法小抄)[贪心]

leetcode 55. 跳跃游戏

题目描述

在这里插入图片描述

解题思路

参考:如何运用贪心思想玩跳跃游戏

每一步都计算一下从当前位置最远能够跳到哪里,然后和一个全局最优的最远位置 farthest 做对比,通过每一步的最优解,更新全局最优解

class Solution {
    public boolean canJump(int[] nums) {
        int n = nums.length;
        int farest = 0;
        for (int i = 0; i < n - 1; i++) {
            /* 每一步都计算一下从当前位置最远能够跳到哪里 */
            farest = Math.max(farest, i + nums[i]);
            /* 可能碰到了 0,卡住跳不动了 */
            if (farest <= i) return false;
        }
        return farest >= n - 1;
    }
}

参考题解:pwrliang的回复

上面这种方法本质上是隐式(implict)BFS,我们维护一个最远能走到的距离farest,在维护该变量的过程中发现它的距离大于等于nums.length-1,那就能够到达末尾。如果看不太懂,放一个显式(explicit)BFS,能通过,只不过非常慢。

class Solution {
    public boolean canJump(int[] nums) {
        Queue<Integer> q = new LinkedList<>();
        boolean[] visited = new boolean[nums.length];
        q.offer(0);
        while(!q.isEmpty()) {
            for(int size=q.size(); size>0; size--) {
                // idx is current position
                int idx = q.remove();
                // if this condition is true, we can find an answer
                if(idx >= nums.length - 1) return true;
                // i is the next rightmost position we can reach
                for(int i=idx + 1; i < nums.length &&
                    i<=idx + nums[idx]; i++) {
                    if(visited[i]) continue;
                    visited[i] = true;
                    q.offer(i);
                }
            }
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值