输入:n = 2, trust = [[1,2]]
输出:2
输入:n = 3, trust = [[1,3],[2,3]]
输出:3
输入:n = 3, trust = [[1,3],[2,3],[3,1]]
输出:-1
输入:n = 3, trust = [[1,2],[2,3]]
输出:-1
输入:n = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
输出:3
本题需要用到有向图中节点的入度和出度的概念。在有向图中,一个节点的入度是指向该节点的边的数量;而一个节点的出度是从该节点出发的边的数量。
每个人相当于一个节点,被人信任相当于指向此人的入度,信任别人相当于出度
var findJudge = function (n, trust) {
const inDegrees = new Array(n + 1).fill(0);
const outDegrees = new Array(n + 1).fill(0);
for (const edge of trust) {
const x = edge[0], y = edge[1];
inDegrees[y]++;
outDegrees[x]++;
}
for (let i = 1; i <= n; ++i) {
if (inDegrees[i] === n - 1 && outDegrees[i] === 0) {
return i;
}
}
return -1;
};