题目描述
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
运行结果
方法二
七桥问题解法直接计算各个节点的入度和出度的差值,得到的差值为N-1的节点为法官,这个方法复杂度为***O(N+len(trust))***,速度明显提升。
参考博客:https://blog.youkuaiyun.com/qq_17550379/article/details/87903873
代码
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
count = [0] * (N + 1)
for i, j in trust:
count[i] -= 1
count[j] += 1
for i in range(1, N + 1):
if count[i] == N - 1:
return i
return -1
运行结果
总结
此博客为博主第一篇博客,希望对在刷LeetCode的各位程序猿们有所帮助。