#leetcode#Course Schedule II
来源:互联网 发布:社交网络 网盘 编辑:程序博客网 时间:2024/05/16 11:46
感觉用BFS来做拓扑排序的做法掌握的差不多了, 但是DFS做法还没写过。。
用了两个hashmap,一个用来存每个节点的入度, 另外一个存当前节点对其指向节点的映射
初始化两个hashmap时i和j的值弄晕了。。
还有最后不要忘记判断是否有有效解
public class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { int[] res = new int[numCourses]; if(prerequisites == null){ return null; } Map<Integer, Integer> indegree = new HashMap<Integer, Integer>(); Map<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); // for(int i = 0; i < prerequisites.length; i++){ // for(int j = 0; j < prerequisites[0].length; j++){ for(int m = 0; m < prerequisites.length; m++){ // prerequisites[i][j], j --> i, indegree of i + 1 int i = prerequisites[m][0]; int j = prerequisites[m][1]; if(!indegree.containsKey(i)){ indegree.put(i, 1); }else{ indegree.put(i, indegree.get(i) + 1); } if(!map.containsKey(j)){ // assume no duplicate pairs ArrayList<Integer> val = new ArrayList<Integer>(); val.add(i); map.put(j, val); }else{ map.get(j).add(i); } // } } Queue<Integer> queue = new LinkedList<Integer>(); for(int k = 0; k < numCourses; k++){ // if(!map.containsKey(k)){ if(indegree.get(k) == null){ queue.offer(k); } } int index = 0; while(!queue.isEmpty()){ int cur = queue.poll(); res[index++] = cur; if(map.containsKey(cur)){ ArrayList<Integer> neighbors = map.get(cur); for(Integer in : neighbors){ if(indegree.containsKey(in)){ indegree.put(in, indegree.get(in) - 1); if(indegree.get(in) == 0){ queue.offer(in); } } } } } if(index != numCourses){ return new int[0]; } return res; }}
0 0
- [leetcode]Course Schedule II
- leetcode - Course Schedule II
- LeetCode Course Schedule II
- [leetcode] Course Schedule II
- leetcode:Course Schedule II
- [LeetCode] Course Schedule II
- Leetcode Course Schedule II
- 【leetcode】Course Schedule II
- leetcode Course Schedule II
- LeetCode Course Schedule II
- [leetcode] Course Schedule II
- #leetcode#Course Schedule II
- LeetCode Course Schedule II
- leetcode Course Schedule II
- Course Schedule II -- leetcode
- Leetcode: Course Schedule II
- [Leetcode] Course Schedule II
- LeetCode -- Course Schedule II
- IOS 调用摄像头
- Linux_4.8_共享内存通信
- Activiti部署流程报错
- 如何建立落地型数据分析(挖掘)流程
- showDialog()、onPrepareDialog()和onCreateDialog()的关系 .
- #leetcode#Course Schedule II
- Go图片上传
- Hnadler的基本使用
- Linux下串口编程入门
- Struts2非常简单实用的身份验证功能
- tomcat,Jboss,weblogic区别,容器的作用 .
- Android 4.4 keyguard类图
- 字符串分割
- QT学习记录(1)环境配置和初步建立项目运行