LeetCode 997. Find the Town Judge
就像之前见过的那道:名人不认识任何其他人 但是所有的其他人都认识这个名人。
现在的规则是法官不相信任何人 但是所有其他人都相信这个法官 这些人之间是否相互信任并不确定。
In a town, there are N people labelled from 1 to N.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
what is the properity of the judge? if [a, b] represents a trust b. and a->b, then the out degree will be 0 and in degree for the N-1.
class Solution {
public int findJudge(int N, int[][] trust) {
if (trust == null || trust.length == 0) {
if (N == 1) {
return 1;
} else {
return -1;
}
}
HashMap<Integer, Integer> in = new HashMap<>(); //in degree of each node
HashMap<Integer, Integer> out = new HashMap<>(); //out degree of each node
for (int[] pair: trust) {
out.put(pair[0], out.getOrDefault(pair[0], 0) + 1);
in.put(pair[1], in.getOrDefault(pair[1], 0) + 1);
}
for (int key = 1; key <= N; key++) {
if (!out.containsKey(key) && in.containsKey(key)) {
if (in.get(key).equals(N - 1)) {
return key;
}
}
}
return -1;
}
}

浙公网安备 33010602011771号