May LeetCoding Challenge10 之 入度出度

本题用两个数组分别记录每个结点的入度和出度。如果结点入度位N-1且出度为0,则该结点是法官。

JAVA

class 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(outdegrees[i] == 0 && indegrees[i] == N-1) return i;
        }
        return -1;
    }
}

Python3

class Solution:
    def findJudge(self, N: int, trust: List[List[int]]) -> int:
        indegrees = [0]*(N+1)
        outdegrees = [0]*(N+1)
        for i, j in trust:
            outdegrees[i] += 1
            indegrees[j] += 1
        for i in range(1, N+1):  #对1到N+1个人进行遍历
            if indegrees[i] == N - 1 and outdegrees[i] == 0: #找到出度为0,入度为N-1的人,即为town judge
                return i
        return -1        

 

posted @ 2020-05-10 17:24  yawenw  阅读(131)  评论(0编辑  收藏  举报