LeetCode-45-跳跃游戏Ⅱ-贪心算法

题目描述:

给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums0。

每个元素 numsi 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 numsi 处,你可以跳转到任意 numsi + j 处:

0 <= j <= numsi

i + j < n

返回到达 numsn - 1 的最小跳跃次数。生成的测试用例可以到达 numsn - 1。

题目详见:LeetCode-45-跳跃游戏Ⅰ

解题思路: 相比55题,这道题难度会增加一点,要返回的是需要跳跃的最小步数,思路还是关注能跳跃的范围,详细步骤:

  1. 需要两个变量,cur:记录当前可以跳跃的步数;next:记录在当前可以跳的步数内可以跳的最大范围
  2. 开始遍历,跳出循环有两种情况:
    ① 当前的已经可以到达数组的最后一个位置;
    ② 当前的cur不能到达数组的最后一个位置。但是走一步后,即更新cur可以到达数组的最后一个位置。
    代码实现:
java 复制代码
class Solution {
    public int jump(int[] nums) {
        int res = 0;// 要跳的步数
        int cur = 0;// 当前可以跳的步数
        int next = 0;
        for (int i = 0; i < nums.length; i++) {
            next = Math.max(next, i + nums[i]);// 在当前可以跳的步数内可以跳的最大范围
            if (cur == i){// 表示已经达到覆盖范围
                if (cur < nums.length-1){//还没有到达数组终点
                    res++;
                    cur = next;// 下一步的覆盖范围 -> 当前覆盖范围
                    if (cur >= nums.length-1){// 更新后的 覆盖范围
                        break;
                    }
                }else {
                    break;
                }
            }
        }
        return res;
    }
}
相关推荐
Nil20814 小时前
leetcode 49字母异位分组
算法·leetcode·哈希算法
Nil2081 天前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_674571971 天前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂1 天前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin7701 天前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao2 天前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1232 天前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi2 天前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2082 天前
leetcode 64最小路径和
算法·leetcode·职场和发展