# Middle-题目118：210. Course Schedule II

124人阅读 评论(0)

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

public class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
if(numCourses==1)
return new int[1];
Map<Integer, Set<Integer>> adjList = new HashMap<Integer,Set<Integer>>();
int[] indegree = new int[numCourses];
for(int i = 0; i<numCourses;i++)
adjList.put(i, new HashSet<Integer>());
for(int[] edge : prerequisites) {
if(!adjList.get(edge[1]).contains(edge[0])) {
adjList.get(edge[1]).add(edge[0]);
indegree[edge[0]]++;
}
}
int[] order = new int[numCourses];
int i=0;
int topoVertical = findZeroIndegree(indegree);
while(topoVertical!=-1) {
indegree[topoVertical] = -1;
for(Integer vertical : adjList.get(topoVertical)) {
if(indegree[vertical]!=-1)
indegree[vertical]--;
}
adjList.remove(topoVertical);
order[i++]=topoVertical;
topoVertical = findZeroIndegree(indegree);
}
if(i==numCourses)
return order;
else
return new int[0];
}

private int findZeroIndegree(int[] indegree) {
for(int i = 0;i<indegree.length;i++)
if(indegree[i]==0) {
return i;
}
return -1;
}
}

37ms,beats 21.31%,众数10ms,8.81%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：55836次
• 积分：3197
• 等级：
• 排名：第10667名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论