-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
32 lines (32 loc) · 974 Bytes
/
Solution.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
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<Integer>[] edges = new List[numCourses];
for (int i = 0; i < numCourses; ++i) {
edges[i] = new ArrayList<>();
}
int[] indegree = new int[numCourses];
for (int[] p : prerequisites) {
edges[p[1]].add(p[0]);
++indegree[p[0]];
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < numCourses; ++i) {
if (indegree[i] == 0) {
q.offer(i);
}
}
int[] res = new int[numCourses];
int cnt = 0;
while (!q.isEmpty()) {
int i = q.poll();
res[cnt++] = i;
for (int j : edges[i]) {
--indegree[j];
if (indegree[j] == 0) {
q.offer(j);
}
}
}
return cnt == numCourses ? res : new int[0];
}
}