链接:https://leetcode.com/problems/course-schedule-ii/
难度:medium
解题思路,优先输出没有前置课程的课,用degrees数组来记录课i的前置课程的数量degrees[i]。当其前置课程数量被选出后,课程的degrees[i] --。剩下就是广搜的思路,每次入队列时只考虑degrees[i] == 0的课程。若最后课程数量不等于numCourses,则说明至少有一门课有循环依赖。
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] degrees = new int[numCourses];
for(int i = 0; i < prerequisites.length; i ++) {
degrees[prerequisites[i][0]] ++;
}
Queue<Integer> queue = new LinkedList<>();
addEle(queue, degrees, numCourses);
int res[] = new int[numCourses];
int visited[] = new int[numCourses];
int i = 0;
while(queue.peek() != null) {
int target = queue.poll();
if(visited[target] == 1) {
continue;
}
res[i ++] = target;
visited[target] = 1;
adjustDegrees(prerequisites, degrees, target);
addEle(queue, degrees, numCourses);
}
if(i < numCourses) return new int[]{};
return res;
}
private void adjustDegrees(int[][] pr,int[] degrees, int target) {
for(int i = 0; i < pr.length; i ++) {
if(pr[i][1] == target) {
degrees[pr[i][0]] --;
degrees[pr[i][1]] --;
}
}
}
private void addEle(Queue<Integer> queue, int[] degrees, int numCourses) {
for(int i = 0; i < numCourses; i ++) {
if(degrees[i] == 0) {
queue.offer(i);
}
}
}
}
Runtime: 38 ms, faster than 6.90% of Java online submissions for Course Schedule II.
Memory Usage: 44.6 MB, less than 93.90% of Java online submissions for Course Schedule II.