File tree Expand file tree Collapse file tree 1 file changed +9
-7
lines changed Expand file tree Collapse file tree 1 file changed +9
-7
lines changed Original file line number Diff line number Diff line change 13
13
* The minimum number of jumps to reach the last index is 2. (Jump 1 step from
14
14
* index 0 to 1, then 3 steps to the last index.)
15
15
*
16
- * Tags: Array, Greedy
16
+ * Tags: Array, Greedy, DP
17
17
*/
18
18
class JumpGame2 {
19
19
public static void main (String [] args ) {
@@ -22,22 +22,24 @@ public static void main(String[] args) {
22
22
23
23
/**
24
24
* Use last to store how far we already can reach
25
+ * Compare i with last
25
26
* If we run out of it, update and add 1 more step to result
26
27
* Return if last is already bigger than or equal to the length
27
28
* Use cur to store how far we can reach for the next step
28
29
*/
29
30
public int jump (int [] A ) {
30
- int res = 0 ;
31
+ int step = 0 ;
31
32
int last = 0 ; // how far we already can reach
32
33
int cur = 0 ; // how far can we reach for next step
34
+
33
35
for (int i = 0 ; i < A .length ; i ++) {
34
- if (i > last ) { // run out of we can reach
36
+ if (i > last ) { // run out of we can reach, need one more step
35
37
last = cur ;
36
- res ++;
37
- if (last >= A .length ) return res ;
38
+ step ++;
39
+ if (last >= A .length ) return step ;
38
40
}
39
41
cur = Math .max (cur , i + A [i ]);
40
42
}
41
- return res ;
43
+ return step ;
42
44
}
43
- }
45
+ }
You can’t perform that action at this time.
0 commit comments