FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/PuzzleCoding/src/JumpGame.java at master · wodgithub/algorithm · GitHub
wodgithub
algorithm
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
JumpGame.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
63 lines (57 loc) · 1.89 KB
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
JumpGame.java
Copy path
File metadata and controls
63 lines (57 loc) · 1.89 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/**
* 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.
* Your goal is to reach the last index in the minimum number of jumps.
* For example:
* Given array A = [2,3,1,1,4]
* The minimum number of jumps to reach the last index is 2.
* (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
*/
public
class
JumpGame
{
public
static
void
main
(
String
[]
args
) {
int
[]
a1
=
new
int
[]{
2
,
3
,
1
,
1
,
4
};
int
[]
a2
=
new
int
[]{
2
,
3
,
1
,
1
,
0
,
4
};
jumpGame
(
a1
);
jumpGame
(
a2
);
}
public
static
void
jumpGame
(
int
[]
a
) {
if
(
a
.
length
==
0
)
return
;
//track the index of previous step
int
[]
previousStep
=
new
int
[
a
.
length
];
for
(
int
i
=
0
;
i
<
previousStep
.
length
;
i
++)
previousStep
[
i
] = -
1
;
boolean
reachEnd
=
false
;
int
furthest
=
a
[
0
];
int
i
=
0
;
while
(
i
<=
furthest
) {
furthest
=
Math
.
max
(
furthest
,
a
[
i
] +
i
);
for
(
int
j
=
0
;
j
<=
furthest
;
j
++) {
if
(
j
<
a
.
length
) {
if
(
previousStep
[
j
] == -
1
)
previousStep
[
j
] =
i
;
else
{
if
(
previousStep
[
j
] >
i
)
previousStep
[
j
] =
i
;
}
}
}
if
(
furthest
>=
a
.
length
-
1
) {
reachEnd
=
true
;
break
;
}
i
++;
}
if
(!
reachEnd
) {
System
.
out
.
println
(
"unreachable!"
);
}
else
{
int
end
=
a
.
length
-
1
;
while
(
end
!=
0
) {
System
.
out
.
print
(
a
[
end
] +
"->"
);
end
=
previousStep
[
end
];
}
System
.
out
.
print
(
a
[
end
]);
System
.
out
.
println
();
}
}
}
Back
|
FazBrowse Home
|
New Git URL