Skip to content

Commit fda5fc2

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 210_Course_Schedule_II.java
1 parent b1f5e8f commit fda5fc2

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed
Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,45 @@
11
class Solution {
22
public int[] findOrder(int numCourses, int[][] prerequisites) {
3-
List<Integer>[] adjList = new ArrayList[numCourses];
3+
Map<Integer, Set<Integer>> graph = new HashMap<>();
44
int[] indegrees = new int[numCourses];
5-
Queue<Integer> q = new LinkedList<>();
65

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]);
99

10-
for (int i = 0; i < numCourses; i++) {
11-
adjList[i] = new ArrayList<>();
10+
indegrees[p[0]]++;
1211
}
1312

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<>();
1815

1916
for (int i = 0; i < indegrees.length; i++) {
2017
if (indegrees[i] == 0) {
2118
q.offer(i);
2219
}
2320
}
2421

22+
int idx = 0;
2523
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+
}
2733

28-
++courseCount;
29-
result[idx++] = course;
34+
for (int neighbour : graph.get(curr)) {
35+
indegrees[neighbour]--;
3036

31-
for (int neighbour : adjList[course]) {
32-
if (--indegrees[neighbour] == 0) {
37+
if (indegrees[neighbour] == 0) {
3338
q.offer(neighbour);
3439
}
3540
}
3641
}
3742

38-
return courseCount == numCourses ? result : new int[] {};
43+
return idx == numCourses ? result : new int[0];
3944
}
4045
}

0 commit comments

Comments
 (0)