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

相关推荐
小白菜又菜1 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
摸个小yu5 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
skywalker_116 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
生信研究猿7 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
XWalnut7 小时前
LeetCode刷题 day9
java·算法·leetcode
6Hzlia7 小时前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
宵时待雨8 小时前
优选算法专题1:双指针
数据结构·c++·笔记·算法·leetcode
We་ct8 小时前
LeetCode 172. 阶乘后的零:从暴力到最优,拆解解题核心
开发语言·前端·javascript·算法·leetcode·typescript
世人万千丶8 小时前
开源鸿蒙跨平台Flutter开发:成语接龙游戏应用
学习·flutter·游戏·华为·开源·harmonyos·鸿蒙
老虎06278 小时前
LeetCode热题100 刷题笔记(第五天)双指针法 「 三数之和 」
笔记·算法·leetcode