题目描述
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], returntrue.
A =[3,2,1,0,4], returnfalse.
分析:对于A,用maxReach记录全局最大跳远位置,然后和当地局部跳远位置比较,更新最大跳远位置。当最大跳远位置小于下一个点的位置时,结束迭代,此时表明无法到达最后一个位置。这个过程为一个贪心的过程。
class Solution {
public:
bool canJump(int A[], int n)
{
int maxReach = 0;
for(int i=0;i<n && i<=maxReach;i++)
maxReach = max(maxReach,i+A[i]); /// 跳到该点后还能到达的极限
if(maxReach<n-1)
return false;
return true;
}
};