leetcode 跳跃游戏 中等

时间:2021-08-08
本文章向大家介绍leetcode 跳跃游戏 中等,主要包括leetcode 跳跃游戏 中等使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本来是用数组标记当前位置时候能够达到,然后表示的从后往前标记,如果发现某个点被标记过了,那么前面点也肯定被标记了,就直接 continue。

然后发现,数组根本没有存在的必要,直接优化掉,维护可达到的最远位置即可。

//class Solution {
//public:
//    bool canJump(vector<int>& nums) {
//        vector<bool> tag(nums.size(), false);
//        tag[0] = true;
//        for(int i = 0; i < nums.size(); ++ i) {
//            if(!tag[i]) return false;
//            for(int j = i + nums[i]; j > i; -- j) {
//                if(tag[j]) continue;;
//                tag[j] = true;
//            }
//        }
//        return tag.back();
//    }
//};

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

原文地址:https://www.cnblogs.com/rookie-acmer/p/15115093.html