There are a total of n courses you have to take, labeled from0ton - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair:[0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Have you met this question in a real interview?

Yes

Example

Given n =2, prerequisites =[[1,0]]
Return[0,1]

Given n = 4, prerequisites =[1,0],[2,0],[3,1],[3,2]]
Return[0,1,2,3]or[0,2,1,3]

  1. same thing as the course schedule i, just put the result into a array
public int[] findOrder(int numCourses, int[][] prerequisites) {
        // Write your code here
        int[] ans = new int[numCourses];
        if (numCourses == 0) {
            return new int[0];
        }

        HashMap<Integer, List<Integer>> courseMap = new HashMap<>();
        int[] preCount = new int[numCourses];

        for (int i = 0; i < numCourses; i++) {
            List<Integer> cur = new ArrayList<>();
            courseMap.put(i, cur);
        }

        for (int i = 0; i < prerequisites.length; i++) {
            preCount[prerequisites[i][0]]++;
            courseMap.get(prerequisites[i][1]).add(prerequisites[i][0]);
        }

        Queue<Integer> queue = new LinkedList<>();
        ArrayList<Integer> ansList = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            if (preCount[i] == 0) {
                queue.offer(i);
                ansList.add(i);
            }
        }

        int count = 0;
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            count++;
            List<Integer> curList = courseMap.get(cur);
            for (int i = 0; i < curList.size(); i++) {
                preCount[curList.get(i)]--;
                if (preCount[curList.get(i)] == 0) {
                    queue.offer(curList.get(i));
                    ansList.add(curList.get(i));
                }
            }
        }

        if (count != numCourses) {
            return new int[0];
        }

        for (int i = 0; i < ansList.size(); i++) {
            ans[i] = ansList.get(i);
        }

        return ans;
    }

results matching ""

    No results matching ""