My 32ms C++ solution with O(n) space


  • 0
    H
    bool cmp(const pair<int,int> & a,const pair<int,int> & b)
    {
        return a.second < b.second;
    }
    
    class Solution {
    public:
        vector<int> findOrder(int num, vector<pair<int, int>>& pre) {
        sort(pre.begin(),pre.end(),cmp);
        vector<int> lim(num+1,-1);
        vector<int> degree(num,0);
        vector<int> ret;
        for(auto x:pre)
            degree[x.first]++;
        for(int i = 1,cnt  = 0; i < pre.size(); i++)
            if(pre[i-1].second!=pre[i].second)
                lim[pre[i-1].second+1] = i;
        if(pre.size())
            lim[pre.back().second+1] = pre.size();
        for(int i = 0,llast = 0; i <= num; i++)
            if(lim[i] < 0)
                lim[i] = llast;
            else 
                llast = lim[i];
        queue<int> que;
        for(int i = 0; i < num; i++)
            if(!degree[i])
                que.push(i);
        for(int j = 0; j < num; j++)
        {
            if(que.empty())
                return vector<int>();
            const int t = que.front();que.pop();
            ret.push_back(t);
            for(int i = lim[t]; i < lim[t+1];  i++)
            {
                degree[pre[i].first]--;
                if(!degree[pre[i].first])
                    que.push(pre[i].first);
            }
        }
        return ret;
    }
    };

Log in to reply
 

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