[220103] Find the Town Judge

这篇博客讨论了一个算法问题,其中涉及识别一个小镇中可能存在的秘密法官。问题基于一个信任网络,其中每个人都信任另一个人。算法首先筛选出被信任次数为n-1的人作为潜在法官,然后验证这个人是否信任其他人。如果找到符合条件的个体,则为法官,否则返回-1表示无法确定。
摘要由CSDN通过智能技术生成

In a town, there are n people labeled 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 an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.

Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.

class Solution:
    def findJudge(self, n, trust):

        cnt = [0] * n

        # 初级筛查,被相信的人放进 hashmap,自己不能相信自己
        for each in trust:
            if each[0] == each[1]:
                return -1
            else:
                cnt[each[1] - 1] += 1

        # 检验有没有人被相信 n-1 次
        for i in range(len(cnt)):
            if cnt[i] == n - 1:
                test = i + 1
                break
        else:
            return -1

        # 检验被相信 n-1 次的人,有没有相信别人
        for each in trust:
            if each[0] == test:
                return -1
        else:
            return test

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值