【Leetcode_总结】997. 找到小镇的法官 - python

Q:

在一个小镇里,按从 1 到 N 标记了 N 个人。传言称,这些人中有一个是小镇上的秘密法官。

如果小镇的法官真的存在,那么:

  1. 小镇的法官不相信任何人。
  2. 每个人(除了小镇法官外)都信任小镇的法官。
  3. 只有一个人同时满足属性 1 和属性 2 。

给定数组 trust,该数组由信任对 trust[i] = [a, b] 组成,表示标记为 a 的人信任标记为 b 的人。

如果小镇存在秘密法官并且可以确定他的身份,请返回该法官的标记。否则,返回 -1

示例 1:

输入:N = 2, trust = [[1,2]]
输出:2

示例 2:

输入:N = 3, trust = [[1,3],[2,3]]
输出:3

链接:https://leetcode-cn.com/problems/find-the-town-judge/

思路:统计一下哪个人被N-1个人信任,并且这个人不信任任何人,如果没有,则返回-1

代码:

class Solution:
    def findJudge(self, N: int, trust: List[List[int]]) -> int:
        if not trust:
            return N
        res = {}
        tmp = []
        for t in trust:
            tmp.append(t[0])
            if t[1] not in res:
                res[t[1]] = 1
            else:
                res[t[1]] += 1
        for k in res:
            if res[k] == N - 1 and k not in tmp:
                return k
        return -1

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/87966947