Day10-Find the Town Judge
问题描述:
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:
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 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.
在一个有N人的小镇上,所有人的标号是从1-N,这个小镇上有一个大法官,这个法官不信任任何人,但是任何人都信任他,让我们找到这个法官,题中给了我们这个小镇的人数和所有人的信任关系。
Example:
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
解法:
给的数组中第一个位置是信任位,第二个位置是被信任位,所以直观的解法就是依题目要求我们设置一个信任和不信任的字典分别存储该人位于信任他人的位置的次数和该人位于被他人信任的位置次数。这样最后我们查看数组就行了,所有的大法官的位置要求处于被信任的位置的次数为N -1 ,位于信任他人的位置的次数为0。
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
#设置一个字典存储每个字符被信任的次数。和信任别人的次数
ts = {}
nots = {}
if N == 1 and trust == []:
return 1
for i in range(len(trust)):
if trust[i][0] in ts:
ts[trust[i][0]] += 1
else:
ts[trust[i][0]] = 1
if trust[i][1] in nots:
nots[trust[i][1]] += 1
else:
nots[trust[i][1]] = 1
for i in nots:
if nots[i] == N -1:
if i not in ts:
return i
return -1
本文介绍了一个有趣的算法问题,即如何在给定的人际信任关系中找出那个不信任任何人却受到所有人信任的小镇法官。通过分析一系列示例,文章详细解释了如何使用Python实现这一算法,并给出了时间复杂度和空间复杂度的评估。
5万+

被折叠的 条评论
为什么被折叠?



