55.Jump Game

时间:2020-05-29
本文章向大家介绍55.Jump Game,主要包括55.Jump Game使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给定一个数组,数组中的数字,代表当前元素的最大跳转值,可以不用跳转到最大的跳转值,比如下标 0 的值为3,可以跳转到下标 1,2,3均可,求,是否能跳转到最后一个下标。

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

思路:
利用一个变量,保存为当前可到达的最大下标值 res,每一次移动,都将之前保存的最大值 res,与当前下标 [i+nums[i]] 比较,保存其中最大的一个。看最后是否能到达终点。
难点:当最大值res = i 时,表示不能往下走了。

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

原文地址:https://www.cnblogs.com/luo-c/p/12987493.html