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.
Analysis:
Note that the A[i] means the maximum jump
length. In other words, it is possible that we move j step (<A[i]) when we at A[i], e.g. if A[i]=2, we can move either 1 or 2 steps.
The simple but time-consuming way is O(n^2). Set every future step true according to the A[i]. But this only can pass the small
test.
A better idea is use another variable to save the number of steps available. Just a little bit different from the O(n^2) one
, see code for more details.
Use one variable to store current maximum jump index
Java
public boolean canJump(int[] A) {
int jmax = 0;
for(int i = 0;i<A.length;i++){
if(i<=jmax){
jmax = Math.max(jmax, A[i]+i);
}else {
return false;
}
}
return true;
}c++
bool canJump(int A[], int n) {
int maxCover = 0;
for(int start = 0; start<=maxCover &&start<n;start++){
if(A[start]+start > maxCover)
maxCover = A[start]+start;
if(maxCover >=n-1)
return true;
}
return false;
}

本文探讨了如何通过算法判断是否能从数组的第一个元素跳到最后一个元素,详细解释了问题的分析过程,并提供了两种实现方式。
254

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



