leetcode 997. Find the Town Judge(小镇的法官)

In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.

Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.

Example 1:

Input: n = 2, trust = [[1,2]]
Output: 2

小镇有1~n的n个人,其中有一个是法官
法官不信任任何人,其他人都相信法官

给出一个数组trust,其中trust[i] = [a, b]表示a信任b
返回法官所在的label,不存在时返回-1

思路:
有向图问题,法官表示入度为n-1,出度为0的节点。
只需要两个数组统计入度和出度即可。

    public int findJudge(int n, int[][] trust) {
        if(n < 1 || trust == null) return -1;
        int[] in = new int[n+1];
        int[] out = new int[n+1];
        
        for(int[] tmp : trust) {
            in[tmp[1]] += 1;
            out[tmp[0]] += 1;
        }
        
        for(int i = 1; i <= n; i++) {
            if(in[i] == n-1 && out[i] == 0) return i;
        }
        
        return -1;
    }

你可能感兴趣的:(leetcode,leetcode,算法,有向图)