|
1 | 1 | class Solution {
|
2 | 2 | public int[] findOrder(int numCourses, int[][] prerequisites) {
|
3 |
| - List<Integer>[] adjList = new ArrayList[numCourses]; |
| 3 | + Map<Integer, Set<Integer>> graph = new HashMap<>(); |
4 | 4 | int[] indegrees = new int[numCourses];
|
5 |
| - Queue<Integer> q = new LinkedList<>(); |
6 | 5 |
|
7 |
| - int courseCount = 0, idx = 0; |
8 |
| - int[] result = new int[numCourses]; |
| 6 | + for (int[] p : prerequisites) { |
| 7 | + graph.putIfAbsent(p[1], new HashSet<>()); |
| 8 | + graph.get(p[1]).add(p[0]); |
9 | 9 |
|
10 |
| - for (int i = 0; i < numCourses; i++) { |
11 |
| - adjList[i] = new ArrayList<>(); |
| 10 | + indegrees[p[0]]++; |
12 | 11 | }
|
13 | 12 |
|
14 |
| - for (int[] pair : prerequisites) { |
15 |
| - adjList[pair[1]].add(pair[0]); |
16 |
| - ++indegrees[pair[0]]; |
17 |
| - } |
| 13 | + int[] result = new int[numCourses]; |
| 14 | + Queue<Integer> q = new LinkedList<>(); |
18 | 15 |
|
19 | 16 | for (int i = 0; i < indegrees.length; i++) {
|
20 | 17 | if (indegrees[i] == 0) {
|
21 | 18 | q.offer(i);
|
22 | 19 | }
|
23 | 20 | }
|
24 | 21 |
|
| 22 | + int idx = 0; |
25 | 23 | while (!q.isEmpty()) {
|
26 |
| - int course = q.poll(); |
| 24 | + int curr = q.poll(); |
| 25 | + |
| 26 | + if (indegrees[curr] == 0) { |
| 27 | + result[idx++] = curr; |
| 28 | + } |
| 29 | + |
| 30 | + if (!graph.containsKey(curr)) { |
| 31 | + continue; |
| 32 | + } |
27 | 33 |
|
28 |
| - ++courseCount; |
29 |
| - result[idx++] = course; |
| 34 | + for (int neighbour : graph.get(curr)) { |
| 35 | + indegrees[neighbour]--; |
30 | 36 |
|
31 |
| - for (int neighbour : adjList[course]) { |
32 |
| - if (--indegrees[neighbour] == 0) { |
| 37 | + if (indegrees[neighbour] == 0) { |
33 | 38 | q.offer(neighbour);
|
34 | 39 | }
|
35 | 40 | }
|
36 | 41 | }
|
37 | 42 |
|
38 |
| - return courseCount == numCourses ? result : new int[] {}; |
| 43 | + return idx == numCourses ? result : new int[0]; |
39 | 44 | }
|
40 | 45 | }
|
0 commit comments