题目:
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.
思路:
一开始以为是边界取值问题,使用recursion 大数据超时了。之后发现是技巧题。
设一个最大能取到的 index,然后循环检查最远能得到的值
Code:
public boolean canJump(int[] A) {
int maxPosition = 0;
for(int i = 0; i<=maxPosition && i<A.length;i++){
maxPosition = i+A[i]>maxPosition? i+A[i]:maxPosition;
}
return maxPosition>=A.length-1;
}
备注:
简化判断语句: str = 条件 ? 真 : 假

本文探讨了一个关于数组跳跃能力的问题,通过设定初始位置和每一步的最大跳跃距离,决定是否能够达到数组的最后一个元素。代码实现采用迭代方式,优化跳跃策略,确保在不超出范围的情况下最大化跳跃范围。

504

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



