LeetCode 题解 | 45. Jump Game II(跳跃游戏 贪心 C++)

题目描述(困难难度)

原题链接
LeetCode 题解 | 45. Jump Game II(跳跃游戏 贪心 C++)_第1张图片

算法

(贪心) O ( n ) O(n) O(n)

每次更新最大距离,然后把每一步所能跳的范围作为一个区间,每当 i = = e n d i == end i==end时,则必须要跳一步,如果 e n d end end大于等于 s i z e − 1 size - 1 size1,则可退出for循环
注意:size = 1时直接返回0
LeetCode 题解 | 45. Jump Game II(跳跃游戏 贪心 C++)_第2张图片

时间复杂度是 O ( n ) O(n) O(n),空间复杂度是 O ( 1 ) O(1) O(1)

C++代码

class Solution {
public:
    int jump(vector<int> &nums) {
        
        int steps = 0;
        int end = 0;
        int maxPosition = 0;
        if (nums.size() <= 1) return 0;
        for (int i = 0; i < nums.size(); i++) {
            maxPosition = max(maxPosition, i + nums[i]);
            if (i == end) {
                end = maxPosition;
                steps++;
                if (end >= nums.size() - 1) break;
            }
        }

        return steps;
    }
};

写在最后:我的博客主要是对计算机领域所学知识的总结、回顾和思考,把每篇博客写得通俗易懂是我的目标,分享技术和知识是一种快乐 ,非常欢迎大家和我一起交流学习,有任何问题都可以在评论区留言,也期待与您的深入交流(^∀^●)

你可能感兴趣的:(LeetCode)