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+nums[i]的最大值far,如果在最后满足far>=nums.size()-1,则返回true,否则为false。
代码实现:
class Solution {
public:
bool canJump(vector<int>& nums) {
int far = nums.empty() ? 0 : nums[0];
for(int i = 1; i <= far && far < nums.size() - 1; ++i)
far = max(far, i + nums[i]);
return far >= nums.size() - 1;
}
};