Difficulty:Medium
Description
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
.
Solution
我参考了Linear and simple solution in C++ ,过程比较简单,所以直接上我的代码。
class Solution {
public:
bool canJump(vector<int>& nums) {
int jumpto = 0, i, n = nums.size(); // jumpto记录目前可以跳到的最大的索引号
for (i = 0; i < n && i <= jumpto; ++i) {
// i若大于jumpto,说明我们最远只能跳到jumpto的位置(索引),即不能跳到最后一个索引
jumpto = jumpto < i + nums[i] ? i + nums[i] : jumpto;
}
return i == n;
}
};