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.
维护一个变量up,记录目前所能到达的最远的数组下标,若up大于等于最后的数组下标,则成功,否则失败。
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size() < 2)
return true;
int up = nums[0],i = 0;
while(i < nums.size() - 1){
up = max(i + nums[i],up);
if(up >= nums.size() - 1)
return true;
if(up < ++i)
return false;
}
return false;
}
};
本文介绍了一个经典的算法问题——跳跃游戏。该问题要求判断是否能从数组的起始位置到达最后一个位置,每个元素代表从该位置可以跳跃的最大长度。文章提供了一种有效的解决方案,并通过一个示例类展示了具体的实现细节。

1万+

被折叠的 条评论
为什么被折叠?



