随笔 - 81, 文章 - 0, 评论 - 0, 阅读 - 15109

(medium)LeetCode 210.Course Schedule II

Posted on   骄阳照林  阅读(112)  评论(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.

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

思想:拓扑排序,入度为0的点入队。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
       int[] ret=new int[numCourses];
       int []inDegree=new int[numCourses];
       int len=prerequisites.length;
       //找到入度为0的节点
       for(int i=0;i<len;i++){
           inDegree[prerequisites[i][0]]++;
       }
       Queue<Integer>q=new LinkedList<Integer>();
       for(int i=0;i<numCourses;i++){
           if(inDegree[i]==0)
               q.offer(i);
       }
       int i=-1;
       while(!q.isEmpty()){
           int e=q.poll();
           ret[++i]=e;
           for(int j=0;j<len;j++){
              if(prerequisites[j][1]==e){
                 if(--inDegree[prerequisites[j][0]]==0)
                     q.offer(prerequisites[j][0]);
              }
               
           }
       }
       if(i==numCourses-1)
           return ret;
        else
        return new int[0];
        
   }
  
}

  

 运行结果:

 

编辑推荐:
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 你所不知道的 C/C++ 宏知识
· 聊一聊 操作系统蓝屏 c0000102 的故障分析
阅读排行:
· 不到万不得已,千万不要去外包
· C# WebAPI 插件热插拔(持续更新中)
· 会议真的有必要吗?我们产品开发9年了,但从来没开过会
· 如何打造一个高并发系统?
· 《SpringBoot》EasyExcel实现百万数据的导入导出
点击右上角即可分享
微信分享提示