Loud and Rich

题目
In a group of N people (labelled 0, 1, 2, ..., N-1), each person has different amounts of money, and different levels of quietness.

For convenience, we'll call the person with label x, simply "person x".

We'll say that richer[i] = [x, y] if person x definitely has more money than person y. Note that richer may only be a subset of valid observations.

Also, we'll say quiet[x] = q if person x has quietness q.

Now, return answer, where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]), among all people who definitely have equal to or more money than person x.

答案

class Solution {
    public int[] loudAndRich(int[][] richer, int[] quiet) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        int[] ans = new int[quiet.length];
        Arrays.fill(ans, -1);
        
        // Use a hashmap to speed up a loop happened in each recursion
        for(int i = 0; i < richer.length; i++) {
            int richer_guy = richer[i][0];
            int poorer_guy = richer[i][1];
            List<Integer> list = map.get(poorer_guy);
            if(list == null) {
                list = new ArrayList<Integer>();
                map.put(poorer_guy, list);
            }
            list.add(richer_guy);
        }
        
        for(int i = 0; i < ans.length; i++) {
            recur(i, map, quiet, ans);
        }
        
        return ans;
    }
    
    public void recur(int curr, Map<Integer, List<Integer>> map, int[] quiet, int[] ans) {
        List<Integer> list = map.get(curr);
        // If this has been calculated before(dp)
        if(ans[curr] != -1) return;
        if(list == null) {
            ans[curr] = curr;
            return;   
        }
        ans[curr] = curr;
        int min_quietness = quiet[curr];
        
        for(int i = 0; i < list.size(); i++) {
            int richer_guy = list.get(i);
            recur(richer_guy, map, quiet, ans);
            if(quiet[ans[richer_guy]] < min_quietness) {
                min_quietness = quiet[ans[richer_guy]];
                ans[curr] = ans[richer_guy];
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,917评论 0 23
  • 我和魏先生为了上班方便,买了一张二手电动车。 昨天买回来的,今天下班后魏先生就说要教我骑。本宝宝内心是拒绝的。但是...
    小菠萝的日常阅读 211评论 0 0
  • “你们知道吗,据说执着哥在追楠楠!” “真的!那我们薇呢?” “干我屁事,他爱追谁追谁,我巴不得他们现在就在一起呢...
    二小货阅读 1,098评论 0 1
  • 窗外, 萦绕着谁的梦想? 恍若绿萝缠墙 , 又似云霞满天 — 随那融雪的春, 呼唤候鸟归来的期盼; 随那叶落的秋,...
    陈谦swan阅读 300评论 0 0