LeetCode 997. 找到小镇的法官
题目描述
思路分析
解法一:入度出度统计(推荐)
核心思路:
- 法官入度为 n-1,出度为 0。
- 遍历信任关系,更新入度与出度。
- 扫描找到满足条件的节点。
复杂度分析:
- 时间复杂度:O(n + m),其中 m 表示信任关系数量。
- 空间复杂度:O(n)。
class Solution {
public int findJudge(int n, int[][] trust) {
int[] indeg = new int[n + 1];
int[] outdeg = new int[n + 1];
for (int[] t : trust) {
outdeg[t[0]]++;
indeg[t[1]]++;
}
for (int i = 1; i <= n; i++) {
if (indeg[i] == n - 1 && outdeg[i] == 0) {
return i;
}
}
return -1;
}
}
func findJudge(n int, trust [][]int) int {
indeg := make([]int, n+1)
outdeg := make([]int, n+1)
for _, t := range trust {
outdeg[t[0]]++
indeg[t[1]]++
}
for i := 1; i <= n; i++ {
if indeg[i] == n-1 && outdeg[i] == 0 {
return i
}
}
return -1
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 207. 课程表 | 中等 | 入度 |
| 310. 最小高度树 | 中等 | 入度 |
| 997. 找到小镇的法官 | 简单 | 入度 |
| 1361. 验证二叉树 | 中等 | 入度 |
| 1615. 最大网络秩 | 中等 | 入度 |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!