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.
public class Solution {
public boolean canJump(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if (A.length <= 1)
return true;
int maxLen = 0;
for(int i = 0; i < A.length; i++){
if(i <= maxLen)
maxLen = Math.max(maxLen, i + A[i]);
else
break;
}
return maxLen >= A.length - 1;
}
}
本文探讨了一个算法问题,即在一个数组中,通过分析每个元素的跳跃能力,判断是否能从数组的第一个元素跳跃到最后一个元素。通过实现一个算法解决方案,我们深入理解了跳跃策略和数组遍历的基本原理。
1196

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



