2019年11月7日 星期四

Course Schedule II


Course Schedule II

  • Lintcode : 616 / Leetcode : 210
  • Level : Medium

Problem

There are a total of n courses you have to take, labeled from 0 to n - 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.

Example
Example 1:

Input: n = 2, prerequisites = [[1,0]] 
Output: [0,1]
Example 2:

Input: n = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] 
Output: [0,1,2,3] or [0,2,1,3]

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n)
space: O(n)

Answer

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>> &prerequisites) {
        vector<unordered_multiset<int>> edge(numCourses);
        vector<int> degrees(numCourses, 0);
        for (int i = 0; i < prerequisites.size(); i++) {
            edge[prerequisites[i].second].insert(prerequisites[i].first);
            degrees[prerequisites[i].first]++;
        }
        queue<int> q;
        vector<int> ans;
        for(int i = 0; i < numCourses; i++) {
            if (degrees[i] == 0) q.push(i);
        }
        while (!q.empty()) {
            int h = q.front(); q.pop();
            ans.push_back(h);
            for (auto it = edge[h].begin(); it != edge[h].end(); it++) {
                degrees[*it]--;
                if (degrees[*it] == 0) q.push(*it);
            }
        }
        return ans.size() == numCourses ? ans : vector<int>();
    }
};
tags: topological sorting

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...