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
.
题目大意就是, 能不能从下标为0
的位置,走到下标为n-1
的位置.
用变量res
表示前i
个数能到达的最大位置;对于当前的位置,如果可到达位置超过最大位置,则更新。
class Solution {
public:
bool canJump(vector<int>& nums) {
int res = 0;
for(int i=0; i<=res; ++ i)
{
res = max(res, nums[i]+i);
if(res >= nums.size()-1)
return true;
}
return false;
}
};