16ms 19lines c++


  • 0
    G
    class Solution
    {
    public:
        vector<int> findOrder(int numCourses, vector<pair<int, int>> prerequisites)
        {
            unordered_map<int, vector<int>> hash;
            vector<int> courses(numCourses, 0);
            vector<int> res;
            for(auto p:prerequisites)
            {
                hash[p.second].push_back(p.first);
                ++courses[p.first];
            }
            for(int i = 0;i<courses.size();++i)
                if(courses[i] == 0)
                    res.push_back(i);
            if(res.empty())
                return vector<int>();
            for(int i = 0;i<res.size();++i)
                if(hash.count(res[i]))
                    for(int j = 0;j<hash[res[i]].size();++j)
                        if(--courses[hash[res[i]][j]] == 0)
                            res.push_back(hash[res[i]][j]);
            return res.size() == numCourses?res:vector<int>();
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.