首页 > 代码库 > Jump Game

Jump Game

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.

1. 题目给定输入都是非负整数
2. 用cpos表示当前可以到达的最后一个位置,然后开始以cpos为结尾开始遍历数组,并同时更新cpos(如果i + A[i]大于当前cpos)
3. 如果在推出循环前在某个位置有cval >= n - 1,说明可以到达最后一个元素,所以之际返回true; 否则在循环结束后返回false。


class Solution {
public:
    bool canJump(int A[], int n) {
        if (n < 2) return true;
        int cpos = A[0];
        for (int i = 0; i <= cpos; ++i) {
            int cval = i + A[i];
            if (cval >= n - 1) return true;
            if (cval > cpos) cpos = cval;
        }
        
        return false;
    }
};