Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5995bda

Browse files
solves jump game ii
1 parent bb2a15e commit 5995bda

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
| 39 | [Combination Sum](https://leetcode.com/problems/combination-sum) | [![Java](assets/java.png)](src/CombinationSum.java) | |
4646
| 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii) | [![Java](assets/java.png)](src/CombinationSumII.java) | |
4747
| 43 | [Multiply Strings](https://leetcode.com/problems/multiply-strings) | [![Java](assets/java.png)](src/MultiplyStrings.java) | |
48+
| 45 | [Jump Game II](https://leetcode.com/problems/jump-game-ii) | [![Java](assets/java.png)](src/JumpGameII.java) | |
4849
| 53 | [Maximum SubArray](https://leetcode.com/problems/maximum-subarray) | [![Java](assets/java.png)](src/MaximumSubArray.java) [![Python](assets/python.png)](python/maximum_sum_subarray.py) | |
4950
| 58 | [Length of Last Word](https://leetcode.com/problems/length-of-last-word) | [![Java](assets/java.png)](src/LengthOfLastWord.java) [![Python](assets/python.png)](python/length_of_last_word.py) | |
5051
| 66 | [Plus One](https://leetcode.com/problems/plus-one) | [![Java](assets/java.png)](src/PlusOne.java) [![Python](assets/python.png)](python/plus_one.py) | |

‎src/JumpGameII.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// https://leetcode.com/problems/jump-game-ii
2+
// T: O(n)
3+
// S: O(1)
4+
5+
public class JumpGameII {
6+
public int jump(int[] nums) {
7+
if (nums.length == 1) return 0;
8+
9+
int jumps = 0;
10+
for (int current = 0 ; current < nums.length ; jumps++) {
11+
int maxJumpIndex = current, maxJump = nums[current];
12+
for (int i = current ; i < current + nums[current] + 1 && i < nums.length ; i++) {
13+
if (i == nums.length - 1) return jumps + 1;
14+
int potential = i - current + nums[i];
15+
if (potential > maxJump) {
16+
maxJump = potential;
17+
maxJumpIndex = i;
18+
} else if (potential == maxJump) maxJumpIndex = i;
19+
}
20+
current = maxJumpIndex;
21+
}
22+
return jumps;
23+
}
24+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /