-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq045_JumpGame2.java
More file actions
59 lines (49 loc) · 1.29 KB
/
q045_JumpGame2.java
File metadata and controls
59 lines (49 loc) · 1.29 KB
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
package leetcode_algorithm;
public class q045_JumpGame2 {
public static void main(String[] args) {
System.out.println(new q045_JumpGame2().jump(new int[]{2, 3, 1, 1, 4}));
System.out.println(new q045_JumpGame2().jump2(new int[]{2, 3, 1, 1, 4}));
}
/**
* ½â·¨1(¸öÈ˽ⷨ)
* @param nums
* @return
*/
public int jump(int[] nums) {
int step = 0;
int max = nums[0];
int edge = 0;
for(int i = 1; i<nums.length ;i++) {
if (i > edge) {
edge = max;
step++;
if(edge >= nums.length - 1)
return step;
}
max = Math.max(max, i + nums[i]);
}
return step;
}
/**
*½â·¨2
* @param nums
* @return
*/
public int jump2(int[] nums) {
int maxReach = nums[0];
int edge = 0;
int minstep = 0;
for(int i = 1 ; i< nums.length; i++) {
if (i > edge) {
minstep += 1;
edge = maxReach;
if(edge > nums.length - 1)
return minstep;
}
maxReach = Math.max(maxReach, nums[i] + i);
if(maxReach == i)
return -1;
}
return minstep;
}
}