997. 找到小镇的法官
997. 找到小镇的法官
题目
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 <= 10000 <= trust.length <= 10^4trust[i].length == 2- All the pairs of
trustare unique. ai != bi1 <= ai, bi <= n
题目大意
小镇里有 n 个人,按从 1 到 n 的顺序编号。传言称,这些人中有一个暗地里是小镇法官。
如果小镇法官真的存在,那么:
- 小镇法官不会信任任何人。
- 每个人(除了小镇法官)都信任这位小镇法官。
- 只有一个人同时满足属性 1 和属性 2 。
给你一个数组 trust ,其中 trust[i] = [ai, bi] 表示编号为 ai 的人信任编号为 bi 的人。
如果小镇法官存在并且可以确定他的身份,请返回该法官的编号;否则,返回 -1 。
示例 1:
输入: n = 2, trust = [[1,2]]
输出: 2
示例 2:
输入: n = 3, trust = [[1,3],[2,3]]
输出: 3
示例 3:
输入: n = 3, trust = [[1,3],[2,3],[3,1]]
输出: -1
提示:
1 <= n <= 10000 <= trust.length <= 10^4trust[i].length == 2trust中的所有trust[i] = [ai, bi]互不相同ai != bi1 <= ai, bi <= n
解题思路
初始化数据结构:
- 创建一个
judge数组,长度为n + 1,用来记录每个节点(对应每个人)被信任的次数。judge[i]表示第i个人被信任的次数。 - 使用一个
believer集合来记录所有信任了其他人的人。即,信任关系中的每个a都加入到believer中。
- 创建一个
处理信任关系:
- 遍历
trust数组,针对每个信任关系[a, b]:- 将
judge[b]加 1,表示b被信任了一次。 - 将
a加入到believer集合中,表示a信任了别人。
- 将
- 遍历
寻找法官:
- 法官是一个特殊的个体,他被
n - 1个人信任,并且他自己不信任任何人。因此,遍历judge数组,找到被信任次数等于n - 1且不在believer集合中的人。
- 法官是一个特殊的个体,他被
返回结果:
- 如果找到符合条件的人,返回其编号(即法官编号);如果没有找到符合条件的人,则返回
-1。
- 如果找到符合条件的人,返回其编号(即法官编号);如果没有找到符合条件的人,则返回
复杂度分析
- 时间复杂度:
O(t + n)- 遍历
trust数组的时间复杂度是O(T),其中t是trust数组的长度。 - 遍历
judge数组的时间复杂度是O(n),其中n是人数。
- 遍历
- 空间复杂度:
O(n)judge数组的大小为n + 1,占用O(n)的空间。believer集合最多包含n个人,占用O(n)的空间。
代码
/**
* @param {number} n
* @param {number[][]} trust
* @return {number}
*/
var findJudge = function (n, trust) {
let judge = new Array(n + 1).fill(0),
believer = new Set();
// 处理信任关系
for (let [a, b] of trust) {
judge[b]++;
believer.add(a);
}
// 寻找法官
for (let i = 1; i <= n; i++) {
if (judge[i] == n - 1 && !believer.has(i)) {
return i;
}
}
return -1;
};
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 277 | 搜寻名人 🔒 | 图 双指针 交互 | 🟠 | 🀄️ 🔗 |
