# 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++)
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的碎碎念：

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

## LeetCode 210. Course Schedule II（课程安排）

• jmspan
• 2016年05月04日 17:09
• 380

## leetcode - 210. Course Schedule II

• Quiteen
• 2017年03月26日 13:17
• 185

## Leetcode 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 prere...

## 210. Course Schedule II\199. Binary Tree Right Side View\279. Perfect Squares

Course Schedule II DESCRIPTION IMPLEMENTATION210. Course Schedule IIDESCRIPTIONThere are a total of ...

## 207,210. Course Schedule I, II

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

## 【LeetCode】210. Course Schedule II

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