问题描述:
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.
示例:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
遍历每一个元素,求其能到达的最大的索引值,以该索引值为右边界,不断逼近最大索引值。
过程详见代码:
class Solution {
public:
bool canJump(vector<int>& nums) {
if (nums.empty()) return true;
int index = nums.size() - 1;
int maxi = 0;
for (int i = 0; i <= maxi; i++)
{
if (maxi >= index) return true;
if (!nums[i] && maxi <= i) return false;
if (!nums[i] && maxi > i) continue;
maxi = max(i + nums[i], maxi);
}
return true;
}
};