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 天前
人工智能应用- 搜索引擎:02. 搜索引擎发展史
人工智能·深度学习·神经网络·游戏·搜索引擎·机器翻译
YGGP1 天前
【Golang】LeetCode 189. 轮转数组
开发语言·leetcode·golang
Tisfy1 天前
LeetCode 3379.转换数组:下标取模
算法·leetcode·题解·模拟·取模
骇城迷影1 天前
代码随想录:数组篇
算法·leetcode
YGGP1 天前
【Golang】LeetCode 56. 合并区间
算法·leetcode·职场和发展
haierccc1 天前
2026年贺新春:Reflexive Arcade 游戏合集下载
游戏
We་ct1 天前
LeetCode 61. 旋转链表:题解+思路拆解
前端·算法·leetcode·链表·typescript
sprintzer1 天前
2.06-2.15力扣数学刷题
算法·leetcode·职场和发展
滴滴答滴答答1 天前
LeetCode Hot100 之 17 有效的括号
算法·leetcode·职场和发展
老鼠只爱大米1 天前
LeetCode经典算法面试题 #20:有效的括号(数组模拟法、递归消除法等五种实现方案详细解析)
算法·leetcode··括号匹配·数组模拟法·递归消除法