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> 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 list = map.get(poorer_guy);
            if(list == null) {
                list = new ArrayList();
                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> map, int[] quiet, int[] ans) {
        List 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];
            }
        }
    }
}

你可能感兴趣的:(Loud and Rich)