【Leetcode 每日一题 - 扩展】45. 跳跃游戏 II

问题背景

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

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

  • 0 ≤ j ≤ n u m s i 0 \le j \le numsi 0≤j≤numsi
  • i + j < n i + j \lt n i+j<n

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

数据约束

  • 1 ≤ n u m s . l e n g t h ≤ 1 0 4 1 \le nums.length \le 10 ^ 4 1≤nums.length≤104
  • 0 ≤ n u m s i ≤ 1000 0 \le numsi \le 1000 0≤numsi≤1000
  • 题目保证可以到达 n u m s n − 1 numsn-1 numsn−1

解题过程

经典跳跃问题,可以用 造桥场景 来理解。

题目描述不是很好懂,其实是在每个位置 i i i 上,可以在 1 , n u m s \[ i ] 1, nums\[i] 1,nums\[i] 中选择一个距离 j j j 并从当前位置移动到 i + j i + j i+j 这个位置上。

解决方案是一个比较明显的贪心算法,每次选择能够到达的最远位置来造桥,能尽可能地减少操作次数。

注意要到达的位置是 n − 1 n - 1 n−1,所以循环应该在 i < n − 1 i < n - 1 i<n−1 处结束。通过样例的输出可能会想到在结果上进行修正,但这样是不对的,因为最后造额外的桥是有条件的。

由于题目保证了一定能够实现目标,不需要再做额外的处理,不保证一定能够全覆盖的情形,参见 灌溉花园的最少水龙头数目

具体实现

java 复制代码
class Solution {
    public int jump(int[] nums) {
        int res = 0;
        int curEnd = 0;
        int nextEnd = 0;
        // 由于到达的位置是 n - 1,那么在 n - 2 的位置上有可能进行最后一次操作
        for(int i = 0; i < nums.length - 1; i++) {
            // 在每个位置上更新能够到达的最远边界
            nextEnd = Math.max(nextEnd, i + nums[i]);
            // 如果当前已经不能继续往前走,那么在这个位置上造桥
            if(i == curEnd) {
                curEnd = nextEnd;
                res++;
            }
        }
        return res;
    }
}
相关推荐
圣保罗的大教堂1 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
土豆.exe2 小时前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法
算法·哈希算法
黄河123长江2 小时前
有限Abel群的结构()
算法
阿米亚波2 小时前
【C++ STL】std::unordered_multimap
开发语言·数据结构·c++·笔记·stl
Jerry2 小时前
LeetCode 92. 反转链表 II
算法
骊城英雄3 小时前
Rust从入门到精通-trait
人工智能·算法·rust
可编程芯片开发3 小时前
基于PI控制算法的pwm直流电机控制系统Simulink建模与仿真
算法
怕浪猫4 小时前
2840亿参数只卖白菜价:DeepSeek V4 Flash 正式版上线,Agent 能力暴涨6倍
人工智能·算法
让学习成为一种生活方式4 小时前
苄基异喹啉生物碱糖基转移酶UGT74AN1晶体--Journal of Agricultural and Food Chemistry
人工智能·算法
alphaTao4 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode