博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Course Schedule II
阅读量:5015 次
发布时间:2019-06-12

本文共 2266 字,大约阅读时间需要 7 分钟。

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].

Note:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about .

Solution:

1 public class Solution { 2     public int[] findOrder(int numCourses, int[][] prerequisites) { 3         if (numCourses ==0) 4             return new int[0]; 5  6         int[] preNum = new int[numCourses]; 7         List
> childMap = new ArrayList
>(); 8 for (int i=0;i
());10 }11 12 for (int[] pair : prerequisites) {13 int course1 = pair[0], course2 = pair[1];14 preNum[course1]++;15 childMap.get(course2).add(course1);16 }17 18 // Get init list19 Queue
courseList = new LinkedList
();20 for (int i = 0; i < numCourses; i++)21 if (preNum[i] == 0) {22 courseList.add(i);23 }24 25 int[] resList = new int[numCourses];26 int index = 0;27 while (!courseList.isEmpty()) {28 int course1 = courseList.poll();29 resList[index++] = course1;30 List
childs = childMap.get(course1);31 for (int course2 : childs) {32 preNum[course2]--;33 if (preNum[course2] == 0) {34 courseList.add(course2);35 }36 }37 }38 39 if (index != numCourses) return new int[0];40 return resList;41 }42 }

 

转载于:https://www.cnblogs.com/lishiblog/p/5820423.html

你可能感兴趣的文章
01背包
查看>>
开发一个12306网站要多少钱?技术分析12306合格还是不合格
查看>>
Selenium 入门到精通系列:六
查看>>
HTTP与TCP的区别和联系
查看>>
android 实现2张图片层叠效果
查看>>
我个人所有的独立博客wordpress都被挂马
查看>>
html5——动画案例(时钟)
查看>>
调用Android系统“应用程序信息(Application Info)”界面
查看>>
ios中用drawRect方法绘图的时候设置颜色
查看>>
数据库中的外键和主键理解
查看>>
个人博客03
查看>>
Expression<Func<T,TResult>>和Func<T,TResult>
查看>>
文件缓存
查看>>
关于C语言中return的一些总结
查看>>
Codeforces Round #278 (Div. 2)
查看>>
51. N-Queens
查看>>
Linux 命令 - 文件搜索命令 locate
查看>>
[Grunt] grunt.template
查看>>
Ubuntu最小化桌面快捷键Super+D不生效解决
查看>>
Cookie&Session会话跟踪技术
查看>>