• 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        
  • 相关阅读:
    调试
    node笔记汇总
    移动端布局
    css 易错点总结
    Angular笔记
    CANVAS笔记
    http笔记汇总
    各种环境搭建 软件安装等等 参考网址收录
    js中同步异步,任务队列
    node.js之fs模块
  • 原文地址:https://www.cnblogs.com/yawenw/p/12864234.html
Copyright © 2020-2023  润新知