题目

思路
- 注意是可以跳跃的最大长度,这个长度内的点都可以跳到。
- 依次遍历数组中的每一个位置,实时维护最远可以到达的位置
curFurthest
。
- 对于当前遍历到的位置x,如果它在
curFurthest
的范围内,说明可以从起点通过若干次跳跃到达该位置,因此用x + nums[x]
更新curFurthest
- 如果当前位置x不在curFurthest范围内,则返回false
- 如果
curFurthest
>=数组中的最后一个位置,那就说明最后一个位置可达,直接返回True
代码
class Solution {
public boolean canJump(int[] nums) {
int curFurthest = 0;
for (int i = 0; i < nums.length; i++) {
if (i > curFurthest) {
return false;
}
curFurthest = Math.max(curFurthest, i + nums[i]);
if (curFurthest >= nums.length) {
return true;
}
}
return true;
}
}