In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1.The town judge trusts nobody.
2.Everybody (except for the town judge) trusts the town judge.
3.There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
Example输入:N = 2, trust = [[1,2]]
输出:2
输入:N = 3, trust = [[1,3],[2,3]]
输出:3
输入:N = 3, trust = [[1,3],[2,3],[3,1]]
输出:-1
输入:N = 3, trust = [[1,2],[2,3]]
输出:-1
输入:N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
输出:3
Note
1. 1 <= N <= 1000
2. trust.length <= 10000
3. trust[i] are all different
4. trust[i][0] != trust[i][1]
5. 1 <= trust[i][0], trust[i][1] <= N
解题思路
该题目考察的是离散数学中的有向图,[a,b]指的是一条从a指向b的有向边,换言之,题目意思就是找到一个所有点都指向它的点,即它的入度为N-1,出度为0,而且在有向图中这个点是唯一的。
方法一建立一个degree数组存储1到N各节点的入度和出度,循环遍历trust找到每个数的出度和入度,直到找到入度为N-1,出度为0的点,否则就返回-1。这种方法复杂度为**O(Nlen(trust))***,运行较慢。
代码class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
degree=[]
for i in range(1,N+1):
indegree=0
outdegree=0
for j in range(len(trust)):
if trust[j][0]==i:
outdegree+=1;
if trust[j][1]==i:
indegree+=1;
if indegree==N-1 and outdegree==0:
return i
return -1
运行结果
原创文章 1获赞 1访问量 11
关注
私信
展开阅读全文
作者:喃甲