Description:
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.
Solution:
对于每一个A[i]而言,计算它可以到达的最远位置并标记,如果可以到达最后,则返回true,反之,则返回false。
Code:
class Solution {
public:
bool canJump(vector<int>& nums) {
int l = nums.size();
int i = 0;
for (int reach = 0; i < l && i <= reach; i++)
reach = max(i + nums[i], reach);
return i == l;
}
};