题目如下:
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.
分析如下:
第一个版本
动态规划,O(N²)居然TLE了,囧
//TLE
public class Solution {
public boolean canJump(int[] A) {
boolean [] result = new boolean[A.length];
if(A[0] > 0) {
result[0] = true;
}
for (int i = 1; i < A.length; ++i) {
for (int j =0; j < i; ++j) {
if (result[j] && (j + A[j] >= i)) {
result[i] = true;
break;
}
}
}
return result[result.length - 1];
}
}
第二个版本
类似动态规划,只是找到最终结果就跳出,所以只是有更大的概率比O(N²)好,worst case依然是O(N²)。 实现的时候有一些边界条件的BUG,记录如下:
// Input: [2,0,0]
// Output: false
// Expected: true
//250ms
public class Solution {
public boolean canJump(int[] A) {
if (A.length == 0) return false;
if (A.length == 1) return true;
// BUG1:
// 错误地validate input
// if (A.length ==0 || A[0] == 0) {
// return false;
// }
int maxIndex = A[0];
for (int i = 0; i <= maxIndex; ++i) {
if ((i + A[i]) > maxIndex) {
maxIndex = (i + A[i]);
}
// BUG2 : reach the last index, means ">=" instead of ">"
//if (maxIndex > A.length - 1) {
if (maxIndex >= A.length - 1) {
return true;
}
}
return false;
}
}