【LeetCode】每日一题——997. 找到小镇的法官

目录

题目:

 思路:

方法一 


题目:

在一个小镇里,按从 1 到 n 为 n 个人进行编号。传言称,这些人中有一个是小镇上的秘密法官。

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

小镇的法官不相信任何人。
每个人(除了小镇法官外)都信任小镇的法官。
只有一个人同时满足条件 1 和条件 2 。
给定数组 trust,该数组由信任对 trust[i] = [a, b] 组成,表示编号为 a 的人信任编号为 b 的人。

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

 思路:

 假设你是法官,记录相信你的人,还有你相信的人(当然你不能相信人,所以这个值要为零)

方法一 

class Solution:
    def findJudge(self, n: int, trust: List[List[int]]) -> int:
        inDegrees = Counter(y for _, y in trust)
        outDegrees = Counter(x for x, _ in trust)
        return next((i for i in range(1, n + 1) if inDegrees[i] == n - 1 and outDegrees[i] == 0), -1)

if inDegrees[i] == n - 1 and outDegrees[i] == 0 所有人相信法官,法官不相信任何人

next函数

next()用法:

next(iterator[, default])
iterator – 可迭代对象
default – 可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发 StopIteration 异常。

list_ = [1,2,3,4,5]
it = iter(list_)
next(it,’-1’)
1

next(it,’-1’)
2

next(it,’-1’)
3

next(it,’-1’)
4

next(it,’-1’)
5

next(it,’-1’)
 

 

参考:
python--内置next()函数_我爱我爸妈的博客-CSDN博客_next函数

猜你喜欢

转载自blog.csdn.net/qq_62932195/article/details/122019817