跳跃游戏(LeetCode 55)
public static boolean canJump(int[] nums) {
if (nums.length == 1) {
return true;
}
int cover = 0;
for (int i = 0; i <= cover; i++) {
cover = Math.max(cover, nums[i] + i);
if (cover >= nums.length - 1) {
return true;
}
}
return false;
}
public static boolean canJump2(int[] nums) {
if (nums.length == 1) {
return true;
}
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
for (int i = 1; i < n; i++) {
if( dp[i - 1] > 0 ) {
dp[i] = Math.max(dp[i - 1] - 1 , nums[i] );
} else {
return false;
}
}
return dp[n - 1] >= 0;
}
最短跳跃游戏(LeetCode 45)
public static int jump2(int[] nums) {
int n = nums.length;
if (n == 1) {
return 0;
}
int cover = 0;
int step = 0;
int max = 0;
for (int i = 0; i < nums.length - 1; i++) {
max = Math.max(max, nums[i] + i);
if (i == cover) {
cover = max;
step++;
}
if (cover >= n - 1) {
return step;
}
}
return step;
}