You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
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 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
这道题是说是有N个人,里面有一个小镇法官,要求是法官不相信任何人,而其他所有人都信任法官,现在让我们找出这个法官,不存在的话返回 -1。跟之前那道 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;
}
};
Activity