1、前言
题目描述
2、思路
3、代码
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
int[] ingreedes = new int[numCourses];
int[] top = new int[numCourses];
HashMap<Integer, List<Integer>> adj = new HashMap<>();
Queue<Integer> queue = new LinkedList<>();
for(int i = 0; i < numCourses; i++){
adj.put(i, new ArrayList<>());
}
for(int[] cp : prerequisites){
ingreedes[cp[0]] += 1;
adj.get(cp[1]).add(cp[0]);
}
for(int i = 0; i < numCourses; i++){
if(ingreedes[i] == 0){
queue.offer(i);
}
}
int j = 0;
while(!queue.isEmpty()){
int temp = queue.poll();
top[j++] = temp;
numCourses--;
for(int i : adj.get(temp)){
ingreedes[i] -= 1;
if(ingreedes[i] == 0){
queue.offer(i);
}
}
}
return numCourses == 0 ? top : new int[0];
}
}
网友评论