lintcode(616)安排课程
来源:互联网 发布:日本扫码软件 编辑:程序博客网 时间:2024/06/06 00:03
Description:
你需要去上n门九章的课才能获得offer,这些课被标号为 0
到 n-1
。
有一些课程需要“前置课程”,比如如果你要上课程0,你需要先学课程1,我们用一个匹配来表示他们: [0,1]
给你课程的总数量和一些前置课程的需求,返回你为了学完所有课程所安排的学习顺序。
可能会有多个正确的顺序,你只要返回一种就可以了。如果不可能完成所有课程,返回一个空数组。
Sample:
给定 n = 2
, prerequisites = [[1,0]]
返回 [0,1]
给定 n = 4, prerequisites = [1,0],[2,0],[3,1],[3,2]]
返回 [0,1,2,3]
or [0,2,1,3]
Solution:
ArrayList<HashSet<Integer>>
If finish
Then finish (HashSet)
0
{1,2}
1
{3}
2
{3}
3
{}
Int[] numPre
course
Number of preRequireCoures
0
0
1
1
2
1
3
2
Go through the array prerequisites torecord the course and its followers (if we have finished a, then we can finishb. Push b to HashSet of a). Then record the number of previous required courses(PRC)of each course. If the number is zero, then push it to the sorted courses. Thenwe need to poll out the class and record it in the result, when poll out one course, renew the number of PRC ofthe related course , then check whether it can be offer to the queue. Go againthe last operation until the sorted courses is empty.
public class Solution { /** * @param numCourses a total of n courses * @param prerequisites a list of prerequisite pairs * @return the course order */ public int[] findOrder(int numCourses, int[][] prerequisites) { // Write your code here ArrayList<HashSet<Integer>> record = new ArrayList<HashSet<Integer>>(); for(int i = 0;i<numCourses;i++){ record.add(new HashSet<Integer>()); } for(int i = 0;i<prerequisites.length;i++){ record.get(prerequisites[i][1]).add(prerequisites[i][0]); } int[] numPre = new int[numCourses]; for(int i = 0;i<numCourses;i++){ for(int after : record.get(i)){ numPre[after]++; } } Queue<Integer> sortCourse = new LinkedList<Integer>(); for(int i = 0;i<numCourses;i++){ if(numPre[i] == 0){ sortCourse.offer(i); } } int[] result = new int[numCourses]; int count = 0; while(!sortCourse.isEmpty()){ int current = sortCourse.poll(); for(int after : record.get(current)){ numPre[after]--; if(numPre[after] == 0){ sortCourse.offer(after); } } result[count++] = current; } return count == numCourses ? result : new int[0]; }}
- lintcode(616)安排课程
- LintCode 安排课程
- lintcode安排课程答案
- 安排课程-LintCode
- 课程安排
- 安排课程
- 不合理的课程安排
- 培训课程安排
- 大三大四课程安排
- 培训课程安排
- 培训课程安排
- 培训课程安排
- 培训课程安排
- 培训课程安排
- 培训公司课程安排
- 软件学院课程安排
- LintCode_安排课程
- 学院课程安排系统, 代码
- 剑指Offer——(23)二叉搜索树的后序遍历序列
- Java实战之Java8指南
- 爱测未来开发-巧用模板引擎编写基于参数配置文件的HTTP接口测试工具
- 【DevExpress v17.1新功能预告】WinForms和WPF Diagram控件
- [LeetCode]Longest Increasing Path in a Matrix
- lintcode(616)安排课程
- java中dao层和service层的区别,为什么要用service?
- AIDL基本使用1----调用服务端方法
- 安卓webview和js+html交互利用的addJavascriptInterface和webview.loadUrl("javascript:**");
- 后台管理系统的登陆验证功能
- C++迭代器 iterator
- Python_%r&%s
- version `GLIBC_2.14' not found
- Hibernate继承