x

Course Schedule II

Leetcode #210 | Medium | Топологическая сортировка | BFS | Очередь | Указатель на запись

Идея

Та же Course Schedule, только нужно еще и выдать результат. Трюк: чтобы не выделять память на лист, заводим указатель на запись и обходимся одним массивом.

Big-O

  • Время O(V+E)
  • Память O(V+E)

Код

class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] indegrees = new int[numCourses];
        int[] res = new int[numCourses];
        int write = 0;
        Map<Integer, List<Integer>> 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<Integer>());
            }
            graph.get(prereq).add(depend);
        }

        Queue<Integer> 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[]{};
        }
    }
}
Left-click: follow link, Right-click: select node, Scroll: zoom
x