Leetcode #210 | #Medium | [Топологическая сортировка](../../Методы/Топологическая%20сортировка.md) | [BFS](../../Методы/BFS.md) | [Очередь](../../Структуры/Очередь.md) | [Указатель на запись](../../Методы/Указатель%20на%20запись.md) ## Идея Та же [Course Schedule](Course%20Schedule.md), только нужно еще и выдать результат. Трюк: чтобы не выделять память на лист, заводим указатель на запись и обходимся одним массивом. ## Big-O - Время ```O(V+E)``` - Память ```O(V+E)``` ## Код ```Java class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { int[] indegrees = new int[numCourses]; int[] res = new int[numCourses]; int write = 0; Map> graph = new HashMap<>(); for (int i = 0; i < prerequisites.length; i++) { int depend = prerequisites[i][0]; int prereq = prerequisites[i][1]; indegrees[depend]++; if (!graph.containsKey(prereq)) { graph.put(prereq, new ArrayList()); } graph.get(prereq).add(depend); } Queue queue = new ArrayDeque<>(); for (int i = 0; i < numCourses; i++) { if (indegrees[i] == 0) { queue.offer(i); } } while (queue.size() > 0) { int course = queue.poll(); res[write++] = course; if (!graph.containsKey(course)) { continue; } for (int dependCourse: graph.get(course)) { indegrees[dependCourse]--; if (indegrees[dependCourse] == 0) { queue.offer(dependCourse); } } } if (write == numCourses) { return res; } else { return new int[]{}; } } } ```