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

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

Determine if you are able to reach the last index.

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

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

完全自己做出来的题,吼吼吼,好开心,一会去做matlab的实验

根据题意,很容易想到是要越过0的点,举几个例子:

3,2,1,0 false

3,2,2,0 true

4,2,1,0 true

3,3,1,0 true

说明什么?0左边的只要有一个能越过这个0的就可以。

那么很容易想到,这个算法是将数组以0分割的,分段判断是否能够成立的

判断是否能越过这个点就是pos-i<=A[i] pos表示最右边的0

循环的时候从右往左,不用考虑n-1这个点,这个点是几都无所谓,只要能到就行

class Solution {
public:
    bool canJump(int A[], int n) {
        int pos=n-1;
        if(n<=1)return true;
        bool flag=0;
        bool exist=0;
        for(int i=n-2;i>=0;i--)
        {
            if(A[i]==0&&flag==1)
            {
                if(exist==0)return false;
                pos=i+1;
                flag=0;
                exist=0;
                continue;
            }
            if(A[i]!=0)flag=1;
            if(pos-i<=A[i])exist=1;
        }
        if(exist==0)return false;
        else return true;
    }
};