615. Course Schedule
https://www.lintcode.com/problem/course-schedule/description?_from=ladder&&fromId=1
为什么不可以用 for(int[] prerequisite: prerequisites) 呢 (使用Leetcode上的方法)?因为当 prerequisites 的 length 很大的时候,会超时。所以要定义一个edges[]变量,用来记录每一门课程的后续课程。
要注意数据类型的转换:
int pointer = (int)edges[curr].get(i);
indegree[pointer]--;
public class Solution { /* * @param numCourses: a total of n courses * @param prerequisites: a list of prerequisite pairs * @return: true if can finish all courses or false */ public boolean canFinish(int numCourses, int[][] prerequisites) { // write your code here if(prerequisites == null || prerequisites.length == 0 || prerequisites[0].length == 0) { return true; } List[] edges = new List[numCourses]; int[] indegree = new int[numCourses]; int count = 0; Queue<Integer> queue = new LinkedList<>(); for(int i = 0; i < numCourses; i++) { edges[i] = new LinkedList<>(); } int len = prerequisites.length; for(int i = 0; i < len; i++) { indegree[prerequisites[i][0]]++; edges[prerequisites[i][1]].add(prerequisites[i][0]); } for(int i = 0; i < numCourses; i++) { if(indegree[i] == 0) { queue.offer(i); } } while(!queue.isEmpty()) { int curr = queue.poll(); count++; int n = edges[curr].size(); for(int i = 0; i < n; i++) { int pointer = (int)edges[curr].get(i); indegree[pointer]--; if(indegree[pointer] == 0) { queue.offer(pointer); } } } return count == numCourses; } }
616. Course Schedule II
https://www.lintcode.com/problem/course-schedule-ii/description?_from=ladder&&fromId=1
public class Solution { /* * @param numCourses: a total of n courses * @param prerequisites: a list of prerequisite pairs * @return: the course order */ public int[] findOrder(int numCourses, int[][] prerequisites) { // write your code here int[] result = new int[numCourses]; List[] edges = new List[numCourses]; int[] indegree = new int[numCourses]; int count = 0; Queue<Integer> queue = new LinkedList<>(); for(int i = 0; i < numCourses; i++) { edges[i] = new LinkedList<>(); } int len = prerequisites.length; for(int i = 0; i < len; i++) { indegree[prerequisites[i][0]]++; edges[prerequisites[i][1]].add(prerequisites[i][0]); } for(int i = 0; i < numCourses; i++) { if(indegree[i] == 0) { queue.offer(i); } } while(!queue.isEmpty()) { int curr = queue.poll(); result[count] = curr; count++; int n = edges[curr].size(); for(int i = 0; i < n; i++) { int pointer = (int)edges[curr].get(i); indegree[pointer]--; if(indegree[pointer] == 0) { queue.offer(pointer); } } } if(count != numCourses) { return new int[0]; } return result; } }