forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJumpGameII.java
60 lines (51 loc) · 1.4 KB
/
JumpGameII.java
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
// Soution 1
class Solution {
// Tc : o(n)
// Sc : o(n)
public int jump(int[] nums) {
Queue<Integer> qu = new LinkedList<>();
boolean[] visited = new boolean[nums.length];
qu.offer(0);
int level = 0;
while(!qu.isEmpty()){
int size = qu.size();
while(size-->0){
Integer currIndex = qu.poll();
if(visited[currIndex]){
continue;
}
if(currIndex == nums.length-1){
return level;
}
int maxIndex = Math.min(currIndex + nums[currIndex], nums.length-1);
while(maxIndex>currIndex){
if(!visited[maxIndex]){
qu.offer(maxIndex);
}
maxIndex--;
}
visited[currIndex] = true;
}
level++;
}
return level;
}
}
// Solution 2
class Solution {
// TC : O(n)
// SC : O(1)
public int jump(int[] nums) {
int level =0;
int divider = 0;
int maxReachableIndex = 0;
for(int i=0;i<nums.length;i++){
if(i> divider){
level++;
divider = maxReachableIndex;
}
maxReachableIndex = Math.max(maxReachableIndex, i +nums[i]);
}
return level;
}
}