-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
https://leetcode.com/problems/jump-game/
- Loading branch information
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
interview_prep/algorithm/java/src/main/java/hoa/can/code/gg/Jumping.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package hoa.can.code.gg; | ||
|
||
import java.util.Arrays; | ||
|
||
/** | ||
* https://leetcode.com/problems/jump-game/ | ||
*/ | ||
public class Jumping { | ||
final static int NO_WAY = Integer.MAX_VALUE; | ||
public static boolean canJump(int[] nums) { | ||
int[] memo = new int[nums.length]; | ||
Arrays.fill(memo, -1); | ||
return (minJumps(nums, 0, nums.length - 1, memo) > -1); | ||
} | ||
private static int minJumps(int steps[], int begin, int dest, int[] memo) { | ||
if (begin == dest) | ||
return 0; | ||
if (steps[begin] == 0) | ||
return NO_WAY; | ||
|
||
int minJump = NO_WAY; | ||
for (int step = steps[begin]; step >= 1; --step) { | ||
if (begin + step <= dest) { | ||
minJump = Math.min(minJump, 1 + minJumps(steps, begin + step, dest, memo)); | ||
} | ||
} | ||
return memo[begin] = minJump; | ||
} | ||
} |
23 changes: 23 additions & 0 deletions
23
interview_prep/algorithm/java/src/test/java/hoa/can/code/JumpingTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package hoa.can.code; | ||
|
||
import org.junit.jupiter.api.DisplayName; | ||
import org.junit.jupiter.api.Test; | ||
|
||
import static hoa.can.code.gg.Jumping.canJump; | ||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
public class JumpingTest { | ||
@Test | ||
@DisplayName("ok") | ||
public void yes() { | ||
assertEquals(true, canJump(new int[]{2, 3, 1, 1, 4})); | ||
assertEquals(true, canJump(new int[]{1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9})); | ||
} | ||
|
||
@Test | ||
@DisplayName("nope") | ||
public void no() { | ||
assertEquals(true, canJump(new int[]{0})); | ||
assertEquals(true, canJump(new int[]{0,1})); | ||
} | ||
} |