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

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++)
for(int[] edge : prerequisites) {
indegree[edge[0]]++;
}
}
int[] order = new int[numCourses];
int i=0;
int topoVertical = findZeroIndegree(indegree);
while(topoVertical!=-1) {
indegree[topoVertical] = -1;
if(indegree[vertical]!=-1)
indegree[vertical]--;
}
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的碎碎念：

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目118：210. Course Schedule II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)