题目链接:
力扣https://leetcode-cn.com/problems/find-the-town-judge/
【分析】其实这是一道判断节点入度出度的简单题,但是我给想复杂了。法官只是入度为n-1,出度为0的节点而已。
class Solution {
public int findJudge(int n, int[][] trust) {
int[] in = new int[n + 1], out = new int[n + 1];
int i, res = -1;
for(i = 0; i < trust.length; i++){
in[trust[i][1]]++;
out[trust[i][0]]++;
}
for(i = 1; i <= n; i++){
if(in[i] == n - 1 && out[i] == 0)
res = i;
}
return res;
}
}
【笨办法】再来看看我用的笨方法,首先统计每个节点是否出现在左侧,然后以有点节点为键,将左边节点加入到一个set中,然后挨个判断set中元素的个数。
import java.util.*;
public class Solution {
public int findJudge(int n, int[][] trust) {
if(n == 1 && trust.length == 0) return 1;
int[] cnt = new int[n + 1];
Map<Integer, Set<Integer>> map = new HashMap<>();
int i, l = trust.length, a, b, key, val;
for(i = 0; i < l; i++){
a = trust[i][0];
b = trust[i][1];
cnt[a] = 1;
if(map.containsKey(b)){
map.get(b).add(a);
}else{
map.put(b, new HashSet<>());
map.get(b).add(a);
}
}
int res = -1;
Iterator<Map.Entry<Integer, Set<Integer>>> it = map.entrySet().iterator();
while (it.hasNext()){
Map.Entry<Integer, Set<Integer>> entry = it.next();
key = entry.getKey();
if(cnt[key] == 1) continue;
val = entry.getValue().size();
if(val == n - 1){
res = key;
break;
}
}
return res;
}
}