mirror of https://github.com/doocs/leetcode.git
30 lines
897 B
Java
30 lines
897 B
Java
class Solution {
|
|
public int[] findOrder(int numCourses, int[][] prerequisites) {
|
|
List<Integer>[] g = new List[numCourses];
|
|
Arrays.setAll(g, k -> new ArrayList<>());
|
|
int[] indeg = new int[numCourses];
|
|
for (var p : prerequisites) {
|
|
int a = p[0], b = p[1];
|
|
g[b].add(a);
|
|
++indeg[a];
|
|
}
|
|
Deque<Integer> q = new ArrayDeque<>();
|
|
for (int i = 0; i < numCourses; ++i) {
|
|
if (indeg[i] == 0) {
|
|
q.offer(i);
|
|
}
|
|
}
|
|
int[] ans = new int[numCourses];
|
|
int cnt = 0;
|
|
while (!q.isEmpty()) {
|
|
int i = q.poll();
|
|
ans[cnt++] = i;
|
|
for (int j : g[i]) {
|
|
if (--indeg[j] == 0) {
|
|
q.offer(j);
|
|
}
|
|
}
|
|
}
|
|
return cnt == numCourses ? ans : new int[0];
|
|
}
|
|
} |