【Leetcode】55. Jump Game

题目地址

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。
posted @ 2020-02-16 16:31  南岛的森林  阅读(95)  评论(0编辑  收藏  举报