lintcode(615)Course Schedule
来源:互联网 发布:iphone中的照片导入mac 编辑:程序博客网 时间:2024/06/06 09:03
Description:
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, is it possible for you to finish all courses?
Explanation:
Given n = 2
, prerequisites = [[1,0]]
Return true
Given n = 2
, prerequisites = [[1,0],[0,1]]
Return false
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 true if can finish all courses or false */ public boolean canFinish(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 count = 0; while(!sortCourse.isEmpty()){ int current = sortCourse.poll(); for(int after : record.get(current)){ numPre[after]--; if(numPre[after] == 0){ sortCourse.offer(after); } } count++; } return count == numCourses ? true : false; }}
- lintcode(615)Course Schedule
- 【Course Schedule】Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- Course Schedule
- GSMS-华为应急通讯完美版 ISO文件下载
- 为什么要在密码里加点“盐”
- SQL Server将表数据移动到新的文件/文件组
- JS 跨域问题和解决方案
- js validate remote验证问题
- lintcode(615)Course Schedule
- 【SDOI2017】数字表格
- Oracle 12C 新特性之 sqlplus查看History命令
- TCP和UDP的135、137、138、139、445端口的作用
- 动态范围规划(调整)Dynamic Range Control的一些心得(三)
- oracle 单表备份
- Brtools 参数解释
- Django 模型字段类型总结 (Django Model field types summary)
- 自己在做项目时用easyUI解决的分页的一些东西