55. Jump Game


做题历程:

  1. 之前应该至少做过一遍,本次独立解出,大概耗时10分钟

本题应该算是Greedy算法,一开始没有第一时间想出,想复杂了,不过仔细想了想后,还是想出了。本题的关键点就是设置一个当前能达到的最远点,之后不断更新,到结尾时判断下。。。直接上代码,代码如下:


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

results matching ""

    No results matching ""