LeetCode *** 210. Course Schedule II
来源:互联网 发布:linux是什么系统 编辑:程序博客网 时间:2024/05/19 17:52
题目:
There are a total of n courses you have to take, labeled from 0
ton - 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 abouthow a graph is represented.
分析:
跑了1484ms。。。。。
代码:
class Solution {public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int> res; unordered_map<int,set<int>> record; for(auto req:prerequisites) record[req.first].insert(req.second); queue<int> que; for(int i=0;i<numCourses;++i) if(record.find(i)==record.end())que.push(i); while(!que.empty()){ int tmp=que.front(); que.pop(); res.push_back(tmp); for(unordered_map<int,set<int>>::iterator it=record.begin();it!=record.end();++it) if(((*it).second).find(tmp)!=((*it).second).end()){ ((*it).second).erase(tmp); if(((*it).second).empty())que.push((*it).first); } } return res.size()==numCourses?res:vector<int>(); }};
- [leetcode] 210.Course Schedule II
- Leetcode 210. Course Schedule II
- 210. Course Schedule II LeetCode
- leetcode 210. Course Schedule II
- LeetCode *** 210. Course Schedule II
- leetcode.210. Course Schedule II
- LeetCode 210. Course Schedule II
- 【LeetCode】210. Course Schedule II
- Leetcode 210. Course Schedule II
- LeetCode 210. Course Schedule II
- Leetcode 210. Course Schedule II
- [LeetCode]210. Course Schedule II
- leetcode 210. Course Schedule II
- LeetCode 210. Course Schedule II
- LeetCode 210. Course Schedule II
- 【LeetCode】210. Course Schedule II
- [leetcode]210. Course Schedule II
- leetcode 210. Course Schedule II
- 在一个UILabel中实现不同的字体和颜色
- POJ 3468 A Simple Problem with Integers (树状数组)
- 【POJ】[3273]Monthly Expense
- (2.2.9)Groovy 介绍
- 对UIView 实例方法的探索
- LeetCode *** 210. Course Schedule II
- 定时自动启动任务crontab命令用法
- Shell 脚本知识回顾 (一) —— 基础篇
- 如何更改workbench的快捷键
- [CODEVS1090][NOIP2013]加分二叉树(树形dp)
- 入门Android开发--第一行代码--笔记系列(Service)
- HBase总结(十二)Java API 与HBase交互实例
- Android开发之Bitmap二次采样
- (2.2.9.1)Groovy一些前提知识