[LeetCode] 997. Find the Town Judge

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:
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 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

Example 3:
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1

Constraints:
1 <= n <= 1000
0 <= trust.length <= 104
trust[i].length == 2
All the pairs of trust are unique.
ai != bi
1 <= ai, bi <= n

找到小镇的法官。

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

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

小镇的法官不相信任何人。
每个人(除了小镇法官外)都信任小镇的法官。
只有一个人同时满足属性 1 和属性 2 。
给定数组 trust,该数组由信任对 trust[i] = [a, b] 组成,表示标记为 a 的人信任标记为 b 的人。
如果小镇存在秘密法官并且可以确定他的身份,请返回该法官的标记。否则,返回 -1。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-town-judge
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

这个题跟 277 题 find the celebrity 很类似,是一个关于图的问题,是在有向图里面找唯一的终点的。思路是做一个 hashmap 统计所有人被相信的次数。因为 trust[i] = [a, b] 的意思是 a 相信 b,而且所有的人都相信法官,所以当遇到 trust[i] = [a, b] 的时候,如果 b 是法官,他被相信的次数一定是++;同时 a 就一定不是法官,他被相信的次数就一定要–,因为法官不相信任何人。最后在 hashmap 里被相信次数 = 总人数 - 1 的那个人,就一定是法官。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int findJudge(int n, int[][] trust) {
int[] count = new int[n + 1];
for (int[] t : trust) {
int a = t[0];
int b = t[1];
// a一定不是法官
count[a]--;
count[b]++;
}

for (int i = 1; i <= n; i++) {
if (count[i] == n - 1) {
return i;
}
}
return -1;
}
}

[LeetCode] 997. Find the Town Judge
https://shurui91.github.io/posts/4068024640.html
Author
Aaron Liu
Posted on
May 11, 2020
Licensed under