第十一周LeetCode
来源:互联网 发布:听戏曲的软件 编辑:程序博客网 时间:2024/05/18 03:23
题目
Course Schedule Ⅱ
难度 Medium
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 how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
实现思路
建一个数组记录每个结点(课程)的入度,入度为0的结点就是下一个输出的结点。每次输出一个结点时,就把这个结点指向的点的入度减1,然后再次找入度为0的结点,直到所有点被遍历完。如果还有点没有被输出时已经没有入度为0的点时,就说明找不到这样的顺序,返回空。
实现代码
vector<int> findOrder(int n, vector<pair<int,int>>& edges) { int in[n] = {0}; for (int i = 0; i < edges.size(); i++) { in[edges[i].first]++; } vector<int> ans; bool visit[n]; int count = n; while (count--) { int node = -1; for (int i = 0; i < n; i++) { if (in[i] == 0) { node = i; in[i] = -1; ans.push_back(i); break; } } for (int i = 0; i < edges.size(); i++) { if (edges[i].second == node) { in[edges[i].first]--; } } } return ans; }
- leetcode-python 第十一周
- leetcode-第十一周
- 第十一周LeetCode
- 第十一周LeetCode
- 第十一周LeetCode
- LeetCode题解 第十一周
- 第十一周LeetCode算法题两道
- 补第十一周Leetcode 博客
- leetcode【第十一周】旋转链表
- 第十一周:[Leetcode]474. Ones and Zeroes
- 第十一周:[Leetcode]139. Word Break
- 第十一周 leetcode 135. Candy(Hard)
- Leetcode 392.Is Subsequence(第十一周作业)
- 第十一周
- 第十一周
- 第十一周
- 第十一周
- 第十一周
- lmax.disruptor高效内存消息队列spring整合
- centos搭建lamp php运行环境
- hdu 1003(未完成)
- Featuretools介绍
- 矩阵相乘C语言
- 第十一周LeetCode
- Android USB 驱动分析与开发----编程
- poj 2456 二分
- HBuilder&&WebStorm部分快捷键
- 的风格
- 锤子剪刀布
- poj 3111 K Best 二分
- python 格式化字符串
- 尾插法建立链表分解