标签:
原题链接在这里:https://leetcode.com/problems/course-schedule-ii/
是Course Schedule的进阶版题目。采用的是同一种方法,这里只需要返回一个结果,所以遍历过的节点放入array中即可。
AC Java:
1 public class Solution { 2 public int[] findOrder(int numCourses, int[][] prerequisites) { 3 int [] res = new int[numCourses]; 4 List<Set> adjancyList = new ArrayList<Set>(); 5 for(int i = 0; i<numCourses; i++){ 6 adjancyList.add(new HashSet<Integer>()); 7 } 8 for( int i = 0; i<prerequisites.length; i++){ 9 adjancyList.get(prerequisites[i][1]).add(prerequisites[i][0]); 10 } 11 12 int [] countPost = new int[numCourses]; 13 for(int i = 0; i<adjancyList.size(); i++){ 14 Set<Integer> perSet = adjancyList.get(i); 15 Iterator<Integer> it = perSet.iterator(); 16 while(it.hasNext()){ 17 countPost[it.next()]++; 18 } 19 } 20 for(int i = 0; i<numCourses; i++){ 21 int k = 0; 22 while(k<countPost.length){ 23 if(countPost[k] == 0){ 24 countPost[k] = -1; 25 break; 26 } 27 k++; 28 } 29 if(k == countPost.length){ 30 return new int[0]; 31 } 32 res[i] = k; 33 Set<Integer> descCount = adjancyList.get(k); 34 Iterator<Integer> descIt = descCount.iterator(); 35 while(descIt.hasNext()){ 36 countPost[descIt.next()]--; 37 } 38 } 39 return res; 40 } 41 }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4868728.html