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

相关推荐
Nil2086 小时前
leetcode 394字符串解码
leetcode
一起努力啊~9 小时前
算法题打卡力扣第1658题:将 x 减到 0 的最小操作数(mid)
学习·leetcode
Cccp.12310 小时前
【leetcode】(六) 图和贪心算法
数据结构·算法·leetcode
y1su10 小时前
【Leetcode】1477. 找两个和为目标值且不重叠的子数组
数据结构·后端·算法·leetcode·职场和发展
mmmmath_321 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z21 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
参.商.1 天前
【Day 53】76. 最小覆盖子串
leetcode·golang
虚无的纽扣1 天前
【力扣刷题】第二天:无重复字符的最长字串、移动零问题
算法·leetcode·排序算法
圣保罗的大教堂1 天前
leetcode 3742. 网格中得分最大的路径 中等
leetcode
河南花仙子科技1 天前
小游戏社交裂变功能的高阶设计思路
大数据·科技·游戏