Skip to content

Commit 61ad1e0

Browse files
author
applewjg
committed
jump game I && II
Change-Id: I9d598acee6c78a527d1a5f3617c04da06e715335
1 parent f1bb0b4 commit 61ad1e0

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

JumpGame.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 21, 2014
4+
Problem: Jump Game
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/jump-game/
7+
Notes:
8+
Given an array of non-negative integers, you are initially positioned at the first index of the array.
9+
Each element in the array represents your maximum jump length at that position.
10+
Determine if you are able to reach the last index.
11+
For example:
12+
A = [2,3,1,1,4], return true.
13+
A = [3,2,1,0,4], return false.
14+
15+
Solution: Updated solution: try every reachable index.
16+
Thank to Wenxin Xing for kindly feedback and pointing out my big mistake:)
17+
*/
18+
public class Solution {
19+
public boolean canJump(int[] A) {
20+
int pos = 0, n = A.length;
21+
for (int i = 0; i < n; ++i) {
22+
if (pos >= i) {
23+
pos = Math.max(pos, i + A[i]);
24+
}
25+
}
26+
return pos >= n - 1;
27+
}
28+
}

JumpGameII.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 21, 2014
4+
Problem: Jump Game II
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/jump-game-ii/
7+
Notes:
8+
Given an array of non-negative integers, you are initially positioned at the first index of the array.
9+
Each element in the array represents your maximum jump length at that position.
10+
Your goal is to reach the last index in the minimum number of jumps.
11+
For example:
12+
Given array A = [2,3,1,1,4]
13+
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.)
14+
15+
Solution: Jump to the position where we can jump farthest (index + A[index]) next time.
16+
*/
17+
public class Solution {
18+
public int jump(int[] A) {
19+
int n = A.length;
20+
int last = 0, cur = 0, res = 0;
21+
for (int i = 0; i < n; ++i) {
22+
if (i > last) {
23+
res++;
24+
last = cur;
25+
}
26+
cur = Math.max(cur, i + A[i]);
27+
}
28+
return res;
29+
}
30+
}

0 commit comments

Comments
 (0)