997. Find the Town Judge
Question
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.
Solution
题目可以转换为计算各个顶点的入度和出度。
遍历每条边,并计算边上两个顶点的出度和入度。
如果某个节点的入度为n-1,出度为0,则符合有法官的条件。
否则没有法官,返回-1。
Code
1 | class Solution { |
997. Find the Town Judge
https://xuanhe95.github.io/2022/05/04/997-Find-the-Town-Judge/