-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathJump Game.java
More file actions
58 lines (43 loc) · 1.5 KB
/
Jump Game.java
File metadata and controls
58 lines (43 loc) · 1.5 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
/*
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.
*/
//BFS, can't pass large set, time limit exceeds
public class Solution {
public boolean canJump(int[] A) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
Stack<Integer> stack = new Stack<Integer>();
HashSet<Integer> visited = new HashSet<Integer>();
stack.push(0);
visited.add(0);
while (!stack.isEmpty()) {
int index = stack.pop();
int maxJump = A[index];
if (index + maxJump >= A.length - 1) {
return true;
}
for (int i = 1; i <= maxJump; i++) {
if (!visited.contains(index + i)) {
visited.add(index + i);
stack.push(index + i);
}
}
}
return false;
}
}
//brilliant solution
//use coverage to track how far you can try
public class Solution {
public boolean canJump(int[] A) {
int coverage = 0;
for(int i = 0; i < A.length && i <= coverage; i++)
coverage = Math.max(coverage, A[i] + i);
return coverage >= A.length - 1;
}
}