描述
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.
给定一个数组,数组的元素表示在该位置上最远能跳跃的距离,现在从数组第一个位置开始,问能不能跳到最后一个位置。
分析
当从第
i
个位置起跳时,最远能跳到
代码
class Solution {
public:
bool canJump(vector<int>& nums) {
int index = 0;
for (int i = 0; i <= index && i < nums.size(); i++)
index = max(index, nums[i] + i);
return index >= nums.size() - 1;
}
};