5月挑战Day10-Find the Town Judge(easy)

本文介绍了一个有趣的算法问题,即如何在给定的人际信任关系中找出那个不信任任何人却受到所有人信任的小镇法官。通过分析一系列示例,文章详细解释了如何使用Python实现这一算法,并给出了时间复杂度和空间复杂度的评估。

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

时间复杂度为O(N),空间复杂度为O(N)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值