标签:Town town Example judge pair Judge Input trust leetcode997
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)
标签:Town,town,Example,judge,pair,Judge,Input,trust,leetcode997 来源: https://www.cnblogs.com/yawenw/p/12257553.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。