leetcode 55. jump game

55. Jump Game

Difficulty:: Medium

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.

Example 1:

1
2
3
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

1
2
3
4
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.

Solution

Language: Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class  {
public boolean canJump(int[] nums) {
if (nums == null || nums.length == 0) {
return true;
}
boolean[] dp = new boolean[nums.length];
dp[0] = true;
for (int i = 0; i < nums.length; i++) {
if (dp[i]) {
for (int j = i + 1; j <= Math.min(nums.length - 1, i + nums[i]); j++) {
dp[j] = true;
}
}
}
return dp[nums.length - 1];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class  {
public boolean canJump(int[] nums) {
if (nums == null || nums.length == 0) {
return true;
}
int m = nums.length;
int[] dp = new int[m];
Arrays.fill(dp, 0);
dp[m - 1] = 1;
for (int i = m - 2; i >= 0; i--) {
int furthest = Math.min(i + nums[i], m - 1);
for (int j = i + 1; j <= furthest; j++) {
if (dp[j] == 1) {
dp[i] = 1;
break;
}
}
}
return dp[0] == 1;
}
}