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
.
思路越清晰,代码越简短的题目 越要求optimize
public class Solution {
public boolean canJump(int[] A) {
int l = A.length;
boolean[] b = new boolean[l];
b[0] = true;
int k = 1;
for (int i = 0; i < l-1; i++) {
if((b[i])&&(A[i] != 0)) {
int j = k;
for (; j <= A[i]+i; j++) {
if (j>(l-1)) {
break;
}
b[j] = true;
}
k = j;
}
}
return b[l-1];
}
}
public class Solution {
public boolean canJump(int[] A) {
int l = A.length;
boolean[] b = new boolean[l];
b[0] = true;
int k = 1;
for (int i = 0; i < l-1; i++) {
//应该写成 if((b[i])&&(A[i] != 0))
if((b[i] == true)&&(A[i] != 0)) {
int j = k;
for (; j <= A[i]+i; j++) {
//应该判断的是 j>=l 要break,否则for 循环不能结束
while (j < l) {
b[j] = true;
}
}
k = j;
}
}
return b[l-1];
}
}