美文网首页
贪心九:跳跃游戏II

贪心九:跳跃游戏II

作者: 程一刀 | 来源:发表于2021-06-15 10:28 被阅读0次

题目地址: https://leetcode-cn.com/problems/jump-game-ii/

题目描述: 给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例: 输入: [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是 2。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

说明: 假设你总是可以到达数组的最后一个位置。

参考代码:

class Solution {
public:
    int jump(vector<int>& nums) {
        if (nums.size()== 1) {
            return 0;
        }
        int current = 0; // 当前范围
        int next = 0; // 下一步最大范围
        int step = 0;
        int size = nums.size()-1;
        for (int i = 0; i<=size; i++) {
            if (current >= size) {
                return step;
            }
            next = max(next, i + nums[i]); //下一步能走的最大范围
            if (i == current) {
                step++;
                current = next;
            }
        }
        return step;
    }
};

参考链接: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0045.%E8%B7%B3%E8%B7%83%E6%B8%B8%E6%88%8FII.md

相关文章

  • 贪心九:跳跃游戏II

    题目地址: https://leetcode-cn.com/problems/jump-game-ii/[htt...

  • 贪心九:跳跃游戏

    题目地址: https://leetcode-cn.com/problems/jump-game/[https:...

  • lettcode刷题之贪心

    leetcode刷题,使用python 1, 跳跃游戏 II —— 0045 贪心算法给定一个长度为 n 的 0...

  • 贪心--跳跃游戏

    目录[https://www.jianshu.com/p/85e18c21317a] 题号[https://lee...

  • 跳跃游戏 II

    题目描述 https://leetcode-cn.com/problems/jump-game-ii/ 解 思路 ...

  • 跳跃游戏(贪心->动态规划)

    1.跳跃游戏(55-中) 题目描述:给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个...

  • LeetCode 45. 跳跃游戏 II | Python

    45. 跳跃游戏 II 题目来源:https://leetcode-cn.com/problems/jump-ga...

  • 贪心2

    demo4a:跳跃游戏(medium)----(贪心) 来源:leetcode 55 思路:找第一步能跳跃到的最远...

  • 45. 跳跃游戏 II

    最近比较忙,最近两周都没怎么刷题,趁着周末,小刷两道怡下情哈哈 自己解法 这题因为还有印象,就是贪婪算法,去算当前...

  • 45. 跳跃游戏 II

    给定一个非负整数数组,你最初位于数组的第一个位置。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 你的目标是...

网友评论

      本文标题:贪心九:跳跃游戏II

      本文链接:https://www.haomeiwen.com/subject/vraseltx.html