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
分析:
我们枚举每一位时都在判断是否被染色过(从而决定是否能够到达该点且能否继续往前走),假设在某一瞬间,index=m
的位置已经被染色了,那么 index=n
(n<=m)
的位置肯定已经被染色过了,我们维护一个最右边被染色的点,如果当前枚举点在该点的左侧,那么当前点已经被染色,否则即可停止遍历(因为右边的点再也不可能被染色到了)。
ac代码:
class Solution
{
public:
bool canJump(vector<int>& nums) {
int r=0,i,L=nums.size();
for(i=0;i<L;i++)
{
if(r<i)
return false;
else
{
r=max(r,nums[i]+i);
}
}
return true;
}
};