这道题仍然是利用了拓扑排序的思想,同leetcode207
//写代码的过程中发现对队列的操作还不是很熟悉
先总结一下队列的操作:
add(e);offer(e) //都是向队列中添加元素;
所不同的是第一个方法添加失败的时候(队列满的时候)会抛出异常
第二个方法添加失败的时候会返回false;
remove(),poll() // 都是向队列中删除元素;第二个方法还可以返回返回队首元素;
所不同的地方在于第一个方法如果删除失败 (队列空的时候)就会抛出异常
第二个方法如果删除失败的话返回false;
peek()该方法只返回队首元素,如果为空的话 返回null;
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
//同上一道题一样,只不过是要在排序的过程中将节点输出到结果集中
int[] res=new int[numCourses];
//接下来是想所给的数据应该存储在哪里
//in_degree该数组表示是存储每个节点的入度
int[] in_degree=new int[numCourses];
//除了存储入度之外还要设置一个队列存放我们的入度为0的节点;
//最后判断队列中的个数是否和课程数一致,如果一致则返回我们的结果集,
//否则的话就返回空数组,代表该图中有循环
for(int i=0;i<prerequisites.length;i++){
in_degree[prerequisites[i][0]]++;}
Queue<Integer> q=new LinkedList<>();
for(int i=0;i<numCourses;i++){
if(in_degree[i]==0)
q.add(i);
}
int k=0;
//当队列不空的时候
int count=0;
while(!q.isEmpty()){
int tou=q.remove();
count++;
res[k++]=tou;
for(int j=0;j<prerequisites.length;j++){
if(prerequisites[j][1]==tou){
in_degree[prerequisites[j][0]]--;
if(in_degree[prerequisites[j][0]]==0){
q.add(prerequisites[j][0]);
}
}
}
}
//如果count 等于numcourse的时候就证明该图中没有环;
if(count==numCourses){
return res;
}
return new int[0];
}}