[LeetCode] 997. Find the Town Judge 找出小鎮法官
In a town, there areN
people labelled from1
toN
. There is a rumor that one of these people is secretly the town judge.
If thetown 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 giventrust
, an array of pairstrust[i] = [a, b]
representing that the person labelleda
trusts the person labelledb
.
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 differenttrust[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;
}
};
若沒有想出有向圖出度和入度的解法,也可以使用下面這種方法,思路是這樣的,由於法官是不會相信任何人的,所以前一個位置的人肯定不是法官,則用一個 HashSet 來儲存所有會相信別人的人,然後再用一個 HashMap 來建立某個人和信任該人的所有人的集合,那麼只要找出不在 HashSet 中的人,且有 N-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
類似題目:
參考資料:
https://leetcode.com/problems/find-the-town-judge/
https://leetcode.com/problems/find-the-town-judge/discuss/242938/JavaC%2B%2BPython-Directed-Graph