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

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

Problem

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.

Example

Given n = 2, prerequisites = [[1,0]]

Return [0,1]

Given n = 4, prerequisites = [1,0],[2,0],[3,1],[3,2]]

Return [0,1,2,3] or [0,2,1,3]

Solution

public class Solution {    /*     * @param n: a total of n courses     * @param pre: a list of prerequisite pairs     * @return: the course order     */    public int[] findOrder(int n, int[][] pre) {        // write your code here        ArrayList[] graph = new ArrayList[n];        for (int i = 0; i < n; i++) {            graph[i] = new ArrayList
(); } int[] indegree = new int[n]; for (int i = 0; i < pre.length; i++) { graph[pre[i][1]].add(pre[i][0]); indegree[pre[i][0]]++; } Queue
queue = new LinkedList
(); for (int i = 0; i < n; i++) { if (indegree[i] == 0) queue.add(i); } int[] result = new int[n]; int index = 0; while (!queue.isEmpty()) { int node = queue.poll(); result[index++] = node; ArrayList
list = graph[node]; for (int i = 0; i < list.size(); i++) { int cur = list.get(i); indegree[cur]--; if (indegree[cur] == 0) queue.add(cur); } } return index == n ? result : new int[0]; }}

转载地址:http://sipmx.baihongyu.com/

你可能感兴趣的文章
SpringMVC的REST风格的四种请求方式
查看>>
漫谈 Clustering (1): k-means(转)
查看>>
从零搭建mongo分片集群的简洁方法
查看>>
J2EE环境配置与工具使用
查看>>
bzoj3684: 大朋友和多叉树(拉格朗日反演+多项式全家桶)
查看>>
C#整数三种强制类型转换int、Convert.ToInt32()、int.Parse()的区别
查看>>
【经典算法】第四回:希尔排序
查看>>
css 禁止选中文本
查看>>
bzoj2165
查看>>
烂泥:【解决】NFS服务器使用showmount –e命令报错
查看>>
烂泥:LVM学习之逻辑卷LV及卷组扩容VG
查看>>
9. ZooKeeper之搭建单机模式。
查看>>
紧急维护,阿里云服务器抢修记
查看>>
数字货币相关
查看>>
payload和formData有什么不同?
查看>>
131016
查看>>
第六次作业
查看>>
python 自动化测试HTTP接口
查看>>
题解——loj6280 数列分块入门4 (分块)
查看>>
Nginx配置文件nginx.conf详解
查看>>