Repository navigation
Expand file tree
/
Copy pathP55_Jump_Game.java
More file actions
67 lines (61 loc) · 1.89 KB
/
Copy pathP55_Jump_Game.java
File metadata and controls
67 lines (61 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package solution.medium;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yi-Lo
* 2020/11/11 17:35
* @version 1.0
* @topics Greedy、Array
* @urllink https://leetcode-cn.com/problems/jump-game/
*/
public class P55_Jump_Game {
public static boolean canJump_s1(int[] nums) {
if (nums.length == 1) {
return true;
}
List<Integer> zeros = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) zeros.add(i);
}
if (zeros.size() > 0) {
for (int j = 0; j < zeros.size(); j++) {
int step = 0;
boolean jump = false;
for (int k = zeros.get(j) - 1; k >= 0; k--) {
step++;
if ((nums[k] > step) || (nums[k] == step && zeros.get(j) == nums.length - 1)) {
jump = true;
break;
}
}
if (!jump) {
return false;
}
}
}
return true;
}
public static boolean canJump_s2(int[] nums) {
int rightmost = 0;
for (int i = 0; i < nums.length; i++) {
if (i > rightmost) return false;
rightmost = Math.max(rightmost, i + nums[i]);
}
return true;
}
public static boolean canJump_s3(int[] nums) {
if (nums == null) return false;
int rightmost = nums.length - 1;
for (int i = nums.length - 1; i >= 0; i++) {
if (nums[i] + i >= rightmost) {
rightmost = i;
}
}
return rightmost == 0;
}
public static void main(String[] args) {
System.out.println(canJump_s1(new int[]{2, 0, 0}));
System.out.println(canJump_s1(new int[]{2, 3, 1, 1, 4}));
System.out.println(canJump_s1(new int[]{3, 2, 1, 0, 4}));
}
}