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

题目描述(中等难度)

原题链接在这里插入图片描述

算法

(贪心) O ( n ) O(n)
每次更新最大可到达的位置,如果遍历到当前位置时 i > m a x P o s i t i o n i > maxPosition 说明这个位置不可到达,则返回 f a l s e false

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

C++代码

class Solution {
public:
    bool canJump(vector<int> &nums) {
        int n = nums.size(), maxPosition = 0;
        for (int i = 0; i < n; i++) {
            if (maxPosition < i) return false; 
            maxPosition = max(maxPosition, i + nums[i]);
        }
        return true;
    }
};

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

发布了308 篇原创文章 · 获赞 149 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/105070016