[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
.
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
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
在一个小镇里,按从 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 class Solution { 2 public int findJudge(int N, int[][] trust) { 3 int[] count = new int[N + 1]; 4 for (int[] t : trust) { 5 count[t[0]]--; 6 count[t[1]]++; 7 } 8 for (int i = 1; i <= N; i++) { 9 if (count[i] == N - 1) { 10 return i; 11 } 12 } 13 return -1; 14 } 15 }