在一个小镇里,按从 1 到 n 为 n 个人进行编号。传言称,这些人中有一个是小镇上的秘密法官。
如果小镇的法官真的存在,那么:
小镇的法官不相信任何人。
每个人(除了小镇法官外)都信任小镇的法官。
只有一个人同时满足条件 1 和条件 2 。
给定数组 trust,该数组由信任对 trust[i] = [a, b] 组成,表示编号为 a 的人信任编号为 b 的人。
如果小镇存在秘密法官并且可以确定他的身份,请返回该法官的编号。否则,返回 -1。
思路还是比较清晰的,针对trust[i[1]]做文章即可
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
d = {}
zero = []
one = []
judge = []
if not trust:
if n == 1:
return 1
else:
return -1
for i in trust:
zero.append(i[0])
one.append(i[1])
d[i[1]] = d.get(i[1],0)+1
d = list(d.items())
d.sort(key=lambda x:x[1],reverse = True)
if d[0][1] == n-1 and d[0][0] not in zero:
return d[0][0]
else:
return -1