997.找到小镇的法官
graph, hash table, https://leetcode.cn/problems/find-the-town-judge/
小镇里有 n 个人,按从 1 到 n 的顺序编号。传言称,这些人中有一个暗地里是小镇法官。
如果小镇法官真的存在,那么:
- 小镇法官不会信任任何人。
- 每个人(除了小镇法官)都信任这位小镇法官。
- 只有一个人同时满足属性 1 和属性 2 。
给你一个数组 trust ,其中 trust[i] = [ai, bi] 表示编号为 ai 的人信任编号为 bi 的人。
如果小镇法官存在并且可以确定他的身份,请返回该法官的编号;否则,返回 -1 。
示例 1:
输入:n = 2, trust = [[1,2]]
输出:2示例 2:
输入:n = 3, trust = [[1,3],[2,3]]
输出:3示例 3:
输入:n = 3, trust = [[1,3],[2,3],[3,1]]
输出:-1提示:
1 <= n <= 10000 <= trust.length <= 10^4trust[i].length == 2trust中的所有trust[i] = [ai, bi]互不相同ai != bi1 <= ai, bi <= n
python
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
out_degrees = [0] * (n + 1)
in_degrees = [0] * (n + 1)
for u, v in trust:
out_degrees[u] += 1
in_degrees[v] += 1
for v in range(1, n + 1):
if out_degrees[v] == 0 and in_degrees[v] == n - 1:
return v
return -1python
if n == 1 and not trust:
return 1
trust_others = set()
trusted_by = [0] * (n + 1)
for x, y in trust:
trust_others.add(x)
trusted_by[y] += 1
for i in range(1, n + 1):
if i not in trust_others and trusted_by[i] == n - 1:
return i
return -1