1 """ 2 In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. 3 If the town judge exists, then: 4 The town judge trusts nobody. 5 Everybody (except for the town judge) trusts the town judge. 6 There is exactly one person that satisfies properties 1 and 2. 7 You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. 8 If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. 9 Example 1: 10 Input: N = 2, trust = [[1,2]] 11 Output: 2 12 Example 2: 13 Input: N = 3, trust = [[1,3],[2,3]] 14 Output: 3 15 Example 3: 16 Input: N = 3, trust = [[1,3],[2,3],[3,1]] 17 Output: -1 18 Example 4: 19 Input: N = 3, trust = [[1,2],[2,3]] 20 Output: -1 21 Example 5: 22 Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] 23 Output: 3 24 """ 25 class Solution: 26 def findJudge(self, N, trust): 27 degree = [0]*(N+1) #(N+1)的原因是要存对应1~N个人的度数 28 for i, j in trust: #对每个trust对进行遍历 29 degree[i] -= 1 #第i个人出度减1 30 degree[j] += 1 #第j个人入度加1 31 for i in range(1, N+1): #对1到N+1个人进行遍历 32 if degree[i] == N - 1: #找到出度为0,入度为N-1的人,即为town judge 33 return i 34 return -1 35 36 """ 37 开一个N+1长度的容器。 38 容器的索引是人的序号。 39 把对放入容器里。pair<出度,入度>。 40 遍历数组,更改每个人的出度和入度。 41 最后判断。出度为0,入度 为N-1的就是法官。 42 """ 43 44 45 #自练: 46 #针对图问题,将向量转变成二维矩阵的方法 47 import numpy as np 48 array = np.ones((4, 4))*0 49 N = 4 50 check = [[0 for i in range(N)] for j in range(N)] 51 trust = [[1, 3], [1, 4], [2, 3], [2, 4], [4, 3]] 52 for pair in trust: 53 array[pair[0] - 1][pair[1] - 1] = 1 54 check[pair[0] - 1][pair[1] - 1] = 1 55 print(array) 56 print(check)