Approach 1: Two Arrays1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class Solution {
public int findJudge(int N, int[][] trust) {
if (trust.length < N - 1) return -1;
int[] indegrees = new int[N + 1];
int[] outdegrees = new int[N + 1];
for (int[] relation : trust) {
outdegrees[relation[0]]++;
indegrees[relation[1]]++;
}
for (int i = 1; i <= N; i++) {
if (indegrees[i] == N - 1 && outdegrees[i] == 0) return i;
}
return -1;
}
}
Approach 2: One Array1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public int findJudge(int N, int[][] trust) {
if (trust.length < N - 1) return -1;
int[] trustScores = new int[N + 1];
for (int[] relation : trust) {
trustScores[relation[0]]--;
trustScores[relation[1]]++;
}
for (int i = 1; i <= N; i++) {
if (trustScores[i] == N - 1) return i;
}
return -1;
}
1 | class Graph{ |