【leetcode】55. Jump Game 数组跳转是否能够到达末节点

1. 题目

Given an array of non-negative integers, you are initially positioned at the first index of the array.code

Each element in the array represents your maximum jump length at that position.element

Determine if you are able to reach the last index.it

For example:
A = [2,3,1,1,4], return true.io

A = [3,2,1,0,4], return false.ast

2. 思路

遍历记录下当前能到达的最远的位置,若是能到达n,则必定能达到<n的任何位置
若是当前能到达的位置小于当前的下标,则说明走不下去了,提早中断退出。
第一个点时起点,必定能够达到,先加入进去。
遍历完成以后,看能到达的位置是否覆盖了末节点的位置。class

3. 代码

耗时:12ms遍历

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int overflow = 0; // 当前能够覆盖到的下标
        for (int i = 0; i < nums.size() - 1; i++) {
            if (overflow < i) { return false; }  // 提早中断, 走不下去了
            int k = i + nums[i];
            if (k > overflow) { overflow = k; }
        }
        return overflow >= nums.size() - 1;
    }
};
相关文章
相关标签/搜索