-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path45.java
More file actions
121 lines (112 loc) · 3.21 KB
/
45.java
File metadata and controls
121 lines (112 loc) · 3.21 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
__________________________________________________________________________________________________
1ms
class Solution {
public int jump(int[] nums) {
if(nums == null || nums.length <= 1) return 0;
int curMax = 0;
int nextMax = 0;
int step = 0;
int index = 0;
while(index <= curMax){
while(index <= curMax){
nextMax = Math.max(nextMax, index + nums[index]);
index ++;
}
curMax = nextMax;
step ++;
if(curMax >= nums.length - 1) return step;
}
return 0;
}
}
__________________________________________________________________________________________________
1ms
public class Solution {
public int jump(int[] nums) {
if (nums.length==1) {
return 0;
}
int max=0;
int[] steps=new int[nums.length];
steps[0]=0;
for (int i = 0; i < nums.length-1; i++) {
int n=nums[i];
if (n+i>max) {
int s=steps[i];
for (int j = max+1; j <=n+i; j++) {
if (j<steps.length) {
if (steps[j]==0||steps[j]>s+1) {
steps[j]=s+1;
}
}
}
max=n+i;
}
}
return steps[steps.length-1];
}
}
__________________________________________________________________________________________________
2ms
class Solution {
public int jump(int[] nums) {
int n = nums.length;
int ans = 0;
int cur = 0;
int next = 0;
if (n <= 1) {
return 0;
}
for(int i=0; i<n; i++) {
if(cur >= i) {
next = Math.max(next, nums[i] + i);
if (next >= n-1) {
return ans + 1;
}
} else {
ans++;
cur = next;
i--;
}
}
return -1;
}
}
__________________________________________________________________________________________________
36144 kb
class Solution {
public int jump(int[] nums) {
int len = nums.length;
int step = 0;
int stepmax = 0, nextmax = 0;
int pos = 0;
while(stepmax < len-1){
while(pos <= stepmax){
nextmax = Math.max(nextmax, pos+nums[pos]);
pos ++;
}
step ++;
stepmax = nextmax;
}
return step;
}
}
__________________________________________________________________________________________________
36164 kb
class Solution {
public int jump(int[] nums) {
if(nums.length ==0) return 0;
int steps = 0;
int maxReach = nums[0];
int lastReach =0;
for(int i=0; i<nums.length && i<=maxReach; i++) {
if(lastReach < i) {
steps++;
lastReach = maxReach;
}
maxReach = Math.max(maxReach, i+nums[i]);
}
return steps;
}
}
__________________________________________________________________________________________________