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.
设立flag为当处在i下标的时候,前面所能够达到的所有长度的最大值(因为是最大值,所以0~最大值的所有下标都可以遍历到)。因此,判断最后能够到达的距离是否大于nums.size()-1。
class Solution {
public:
bool canJump(vector<int>& nums) {
int flag=0;
for(int i=0;i<nums.size()&&i<=flag;i++){
flag=max(flag,i+nums[i]);
}
return flag>=nums.size()-1;
}
};

本文介绍了一个经典的算法问题——跳跃游戏。该问题要求判断一个非负整数数组中,从第一个位置出发能否到达最后一个位置。文章详细阐述了解决方案,通过维护一个标志变量来跟踪能够达到的最大距离,并最终判断是否能覆盖整个数组。
696

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



