2025年leetcode 55. 跳跃游戏

leetcode 55. 跳跃游戏labuladong 的算法小抄 贪心 leetcode 55 跳跃游戏 题目描述 解题思路 参考 如何运用贪心思想玩跳跃游戏 每一步都计算一下从当前位置最远能够跳到哪里 然后和一个全局最优的最远位置 farthest 做对比 通过每一步的最优解 更新全局最优解 class

大家好,我是讯享网,很高兴认识大家。

@(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; } } 
小讯
上一篇 2025-01-19 07:01
下一篇 2025-03-22 17:11

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/105291.html