首页 > 其他 > 详细

【Leetcode】55. Jump Game

时间:2020-02-16 17:20:53      阅读:71      评论:0      收藏:0      [点我收藏+]

题目地址

https://leetcode.com/problems/jump-game/

题目大意

https://leetcode-cn.com/problems/jump-game/

解题思路

维护当前可以跳到的最远位置maxIndex。遍历nums,如果当前索引i不超过maxIndex, 表示可以到达索引i处,否则直接返回false, 即该位置不可达。如果当前位置可达且从当前位置跳到的最远位置大于maxIndex, 则更新maxIndex。

C++代码

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

复杂度

  1. 时间复杂度:O(n), 遍历nums。
  2. 空间复杂度:O(1), 需要维护最远可达位置maxIndex。

【Leetcode】55. Jump Game

原文:https://www.cnblogs.com/AndrewGhost/p/12317326.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!