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,表示最少需要跳跃两次。

相关推荐
TracyCoder12316 分钟前
LeetCode Hot100(57/100)——5. 最长回文子串
算法·leetcode·职场和发展
WZ1881046386921 分钟前
LeetCode第20题
算法·leetcode
吕司33 分钟前
LeetCode Hot Code——三数之和
数据结构·算法·leetcode
YGGP1 小时前
【Golang】LeetCode 54. 螺旋矩阵
算法·leetcode·矩阵
十八岁讨厌编程1 小时前
【算法训练营 · 二刷总结篇】贪心算法、图论部分
算法·贪心算法·图论
TracyCoder1231 小时前
LeetCode Hot100(58/100)——138. 随机链表的复制
leetcode·链表
Frostnova丶2 小时前
LeetCode 868. 二进制间距
算法·leetcode
WZ188104638692 小时前
LeetCode第54题
算法·leetcode
丰海洋2 小时前
Leetcode-hot100-136只出现一次的数字
算法·leetcode·职场和发展
We་ct2 小时前
LeetCode 124. 二叉树中的最大路径和:刷题解析
前端·数据结构·算法·leetcode·typescript