leetcode 851. Loud and Rich

 

class Solution {
    int dfs(vector<int>&res,int i,vector<int>& quiet,map<int,vector<int>>& m){
        if(res[i]>0) return res[i];
        res[i]=i;
        for(int j=0;j<m[i].size();++j){
            if(quiet[res[i]]>quiet[dfs(res,m[i][j],quiet,m)])
                res[i]=res[m[i][j]];
        }
        return res[i];
    }
public:
    vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
        map<int,vector<int>> m;
        for(auto& v: richer){
            m[v[1]].push_back(v[0]);
        }
        vector<int> res=vector<int>(quiet.size(),-1);
        for(int i=0;i<quiet.size();++i){
            dfs(res,i,quiet,m);
        }
        return res;
    }
};

 python代码

class Solution(object):
    def loudAndRich(self, richer, quiet):
        """
        :type richer: List[List[int]]
        :type quiet: List[int]
        :rtype: List[int]
        """
        m=collections.defaultdict(list)
        for i,j in richer:
            m[j].append(i)
        res=[-1]*len(quiet)
        def dfs(i):
            if res[i]>0:
                return res[i]
            res[i]=i
            for j in m[i]:
                if quiet[res[i]]>quiet[dfs(j)]:
                    res[i]=res[j]
            return res[i]
        for i in range(len(res)):
            dfs(i)
        return res
        

 

posted @ 2018-10-03 17:47  hopskin1  阅读(186)  评论(0编辑  收藏  举报