Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8d87bb3

Browse files
committed
added leetcode daily challenge task #1345 from 3/5/2023
1 parent 5a4edbc commit 8d87bb3

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/task_1345/Solution.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package task_1345;
2+
3+
import java.util.Map;
4+
import java.util.HashMap;
5+
import java.util.List;
6+
import java.util.Queue;
7+
import java.util.LinkedList;
8+
import java.util.ArrayList;
9+
10+
public class Solution {
11+
12+
public int minJumps(int[] arr) {
13+
int n = arr.length;
14+
if (n == 1) {
15+
return 0;
16+
}
17+
Map<Integer, List<Integer>> indices = new HashMap<>();
18+
for (int i = 0; i < n; i++) {
19+
indices.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
20+
}
21+
Queue<Integer> storeIndex = new LinkedList<>();
22+
boolean[] visited = new boolean[n];
23+
storeIndex.offer(0);
24+
visited[0] = true;
25+
int steps = 0;
26+
while (!storeIndex.isEmpty()) {
27+
int size = storeIndex.size();
28+
while (size-- > 0) {
29+
int currIndex = storeIndex.poll();
30+
if (currIndex == n - 1) {
31+
return steps;
32+
}
33+
List<Integer> jumpNextIndices = indices.get(arr[currIndex]);
34+
jumpNextIndices.add(currIndex - 1);
35+
jumpNextIndices.add(currIndex + 1);
36+
for (int jumpNextIndex : jumpNextIndices) {
37+
if (jumpNextIndex >= 0 && jumpNextIndex < n && !visited[jumpNextIndex]) {
38+
storeIndex.offer(jumpNextIndex);
39+
visited[jumpNextIndex] = true;
40+
}
41+
}
42+
jumpNextIndices.clear();
43+
}
44+
steps++;
45+
}
46+
return -1;
47+
}
48+
49+
}

0 commit comments

Comments
 (0)