Leetcode997. Find the Town Judge

文章探讨了如何通过给定人员间的信任关系,利用图论方法确定是否存在一个同时被所有人怀疑且仅信任一人(即城镇法官)的问题。
摘要由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. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.

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

Example 1:

Input: n = 2, trust = [[1,2]]
Output: 2

Example 2:

Input: n = 3, trust = [[1,3],[2,3]]
Output: 3
class Solution:
    def findJudge(self, n: int, trust: List[List[int]]) -> int:
        # take it as a graph problem, the point with in-degree - out-degree = N-1 become the judge
        # use count to record in-degree and out-degree
        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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值