In a town, there are
n
people labeled from1
ton
. 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 an array
trust
wheretrust[i] = [ai, bi]
representing that the person labeledai
trusts the person labeledbi
.Return the label of the town judge if the town judge exists and can be identified, or return
-1
otherwise.
class Solution:
def findJudge(self, n, trust):
cnt = [0] * n
# 初级筛查,被相信的人放进 hashmap,自己不能相信自己
for each in trust:
if each[0] == each[1]:
return -1
else:
cnt[each[1] - 1] += 1
# 检验有没有人被相信 n-1 次
for i in range(len(cnt)):
if cnt[i] == n - 1:
test = i + 1
break
else:
return -1
# 检验被相信 n-1 次的人,有没有相信别人
for each in trust:
if each[0] == test:
return -1
else:
return test