首页 > 其他 > 详细

May LeetCoding Challenge10 之 入度出度

时间:2020-05-10 19:46:24      阅读:54      评论:0      收藏:0      [点我收藏+]

本题用两个数组分别记录每个结点的入度和出度。如果结点入度位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        

 

May LeetCoding Challenge10 之 入度出度

原文:https://www.cnblogs.com/yawenw/p/12864234.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!