997. Find the Town Judge

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

If the town judge exists, then:

1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties 1 and 2.

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`.

Example 1:

``````Input: N = 2, trust = [[1,2]]
Output: 2
``````

Example 2:

``````Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
``````

Example 3:

``````Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
``````

Example 4:

``````Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
``````

Example 5:

``````Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
``````

Constraints:

• `1 <= N <= 1000`
• `0 <= trust.length <= 10^4`
• `trust[i].length == 2`
• `trust[i]` are all different
• `trust[i][0] != trust[i][1]`
• `1 <= trust[i][0], trust[i][1] <= N`

Find the Celebrity 非常相似，那道题是所有人都认识名人，但是名人不认识任何人。而这里是法官不相信人任何人，而所有人都相信法官，不同的是在于给的数据结构不同，名人那道是给了个 API 判断是否认识，而这里给了个信任数组，那么解法就稍有不同了。由于信任是有方向的，所以是一个有向图，因为法官不相信任何人，所以其没有出度，而所有人都信任他，则入度满值。最简单直接的方法就是统计每个结点的出度和入度，然后找出那个出度为0，入度为 N-1 的结点即可，参见代码如下：

``````class Solution {
public:
int findJudge(int N, vector<vector<int>>& trust) {
vector<int> in(N + 1), out(N + 1);
for (auto a : trust) {
++out[a[0]];
++in[a[1]];
}
for (int i = 1; i <= N; ++i) {
if (in[i] == N - 1 && out[i] == 0) return i;
}
return -1;
}
};
``````

``````class Solution {
public:
int findJudge(int N, vector<vector<int>>& trust) {
unordered_set<int> st;
unordered_map<int, vector<int>> beTrustedMap;
for (auto &a : trust) {
st.insert(a[0]);
beTrustedMap[a[1]].push_back(a[0]);
}
for (int i = 1; i <= N; ++i) {
if (st.count(i)) continue;
if (beTrustedMap[i].size() == N - 1) return i;
}
return -1;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/997

Find the Celebrity

https://leetcode.com/problems/find-the-town-judge/

https://leetcode.com/problems/find-the-town-judge/discuss/242938/JavaC%2B%2BPython-Directed-Graph

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation