997. Find the Town Judge

T: O(t + n)

S: O(n)

```java
class Solution {
    public int findJudge(int n, int[][] trust) {
        if (n == 1) {
            return 1;
        }
        int[] outDegree = new int[n+1];
        int[] inDegree = new int[n+1];
        for (int i = 0; i < trust.length; i++) {
            outDegree[trust[i][0]]++;
            inDegree[trust[i][1]]++;
        }
        for (int i = 1; i <= n; i++) {
            if (outDegree[i] == 0 && inDegree[i] == n-1) {
                return i;
            }
        }
        return -1;
    }
}

/*


1 -> 2

1 -> 3
2. -> 3


1 -> 3
2 ->
3 -> 1


1->2
2->3
3->x

not every one trust
*/
```

judge: only count "in-degree - out-degree = N - 1"

```java
class Solution {
    public int findJudge(int n, int[][] trust) {
        if (n == 1) {
            return 1;
        }
        // in-degree - out-degree = N - 1
        int[] degree = new int[n+1];
        for (int i = 0; i < trust.length; i++) {
            degree[trust[i][0]]--;
            degree[trust[i][1]]++;
        }
        for (int i = 1; i <= n; i++) {
            if (degree[i] == n-1) {
                return i;
            }
        }
        return -1;
    }
}
```

Last updated