213.贪心算法:跳跃游戏||(力扣)

cpp 复制代码
class Solution {
public:
    int jump(vector<int>& nums) 
    {
        if (nums.size() == 1) return 0; // 如果数组长度为1,已经在终点,不需要跳跃

        int cur = 0;   // 当前跳跃能到达的最远位置
        int flag = 0;  // 记录跳跃次数
        int next = 0;  // 下一次跳跃能到达的最远位置
        
        for (int i = 0; i < nums.size(); i++)
        {
            next = max(i + nums[i], next); // 更新下一次跳跃能到达的最远位置
            
            if (i == cur) // 当遍历到当前跳跃的最远位置时
            {
                flag++;   // 增加跳跃次数
                cur = next; // 更新当前跳跃的最远位置
                
                if (next >= nums.size() - 1) break; // 如果下一次跳跃能到达终点,结束循环
            }
        }
        
        return flag; // 返回跳跃次数
    }
};

核心思想

该算法使用贪心策略,每次选择当前能跳跃的最远位置,并更新下一次能跳跃的最远位置。遍历过程中,每当到达当前能跳跃的最远位置时,增加跳跃次数,并更新当前跳跃能到达的最远位置。如果在更新过程中,发现能到达或超过终点,跳出循环。

示例

考虑 nums = [2, 3, 1, 1, 4]

  • 初始 cur = 0flag = 0next = 0
  • 第一次循环:
    • i = 0next = max(0 + 2, 0) = 2
    • i == cur,跳跃次数增加:flag = 1,更新 cur = next = 2
  • 第二次循环:
    • i = 1next = max(1 + 3, 2) = 4
    • i == cur,跳跃次数增加:flag = 2,更新 cur = next = 4
    • 终点可达,跳出循环

最终返回 flag = 2,表示最少需要跳跃两次。

相关推荐
星星码️2 小时前
LeetCode刷题简单篇之反转字母
c++·算法·leetcode
阿斯加德D5 小时前
天国:拯救 2风灵月影修改器下载(已汉化)2026最新版下载分享
测试工具·游戏·3d·游戏程序
sheeta19985 小时前
LeetCode 每日一题笔记 日期:2026.05.10 题目:2770. 达到末尾下标所需的最大跳跃次数
笔记·算法·leetcode
YF02116 小时前
Android 物理摇杆按键映射技术详解
android·游戏
shehuiyuelaiyuehao6 小时前
算法21,搜索插入位置
python·算法·leetcode
_深海凉_7 小时前
LeetCode热题100-回文链表
算法·leetcode·链表
小雅痞7 小时前
[Java][Leetcode middle] 54. 螺旋矩阵
java·leetcode·矩阵
pursuit_csdn7 小时前
力扣周赛 501
算法·leetcode·职场和发展
AbandonForce7 小时前
LeetCode 滑动窗口个人思路详解
算法·leetcode·职场和发展
Liangwei Lin7 小时前
LeetCode 45. 跳跃游戏 II
数据结构·算法·leetcode