算法题目: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.
大致题意:给定一个非负整数数组,表示在各位置上的所能跳跃的最大长度,假设你被放在数组的起始位置,判断是否能够到达末尾。
解法:利用数posmax表示当前能够到达的最大位置,在当前位置与posmax之间进行遍历更新posmax的值,最后若posmax>=数组的长度则表示可以到达。
bool canJump(vector<int>& nums) {
if(nums.size()==0)return false;
int posmax=0;
for(int i=0;i<=posmax&&posmax<nums.size();i++)
{
posmax=max(i+nums[i],posmax);
}
return posmax>=nums.size()-1;
}