forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse Schedule II.java
More file actions
29 lines (29 loc) · 963 Bytes
/
Course Schedule II.java
File metadata and controls
29 lines (29 loc) · 963 Bytes
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
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
Map<Integer, List<Integer>> map = new HashMap<>();
int[] prereqCount = new int[numCourses];
for (int[] prerequisite : prerequisites) {
prereqCount[prerequisite[0]]++;
map.computeIfAbsent(prerequisite[1], k -> new ArrayList<>()).add(prerequisite[0]);
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (prereqCount[i] == 0) {
queue.add(i);
}
}
int[] ans = new int[numCourses];
int idx = 0;
while (!queue.isEmpty()) {
int removed = queue.remove();
for (Integer dependentCourse : map.getOrDefault(removed, new ArrayList<>())) {
prereqCount[dependentCourse]--;
if (prereqCount[dependentCourse] == 0) {
queue.add(dependentCourse);
}
}
ans[idx++] = removed;
}
return idx == numCourses ? ans : new int[]{};
}
}