describe

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.

If the town judge exists, then:

  • The town judge trusts nobody.
  • Everybody (except for the town judge) trusts the town judge.
  • There is exactly one person that satisfies properties 1 and 2.

You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.

If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.

Example 1:

Input: N = 2, trust = [[1,2]]
Output: 2	
Copy the code

Example 2:

Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Copy the code

Example 3:

Input: N = 3, trust = [[1, 3], [2, 3], [3, 1]] Output: 1Copy the code

Example 4:

Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Copy the code

Example 5:

Input: N = 4, trust = [[1, 3], [1, 4], [2, 3], [2, 4], [4]] Output: 3Copy the code

Note:

1 <= N <= 1000 0 <= trust.length <= 10^4 trust[i].length == 2 trust[i] are all different trust[i][0] ! = trust[i][1] 1 <= trust[i][0], trust[i][1] <= NCopy the code

parsing

To find the hidden judge in the town, the judge must be satisfied that everyone else trusts him. So now we have a trust list that says A trusts B, so we can count everyone. Using a list D of length N+1 for everyone (the element with index 0 is useless, and the other indexes represent everyone in town), and then traversing each sub-list in trust [a,b], d[a]-=1 to indicate that he is definitely not a judge if he believes someone else, D [b]+=1 indicates that he is believed to be a judge. After traversal, as long as the count of the position in D is n-1, it indicates that it is a judge. Return its index, otherwise return -1.

answer

 class Solution(object):
    def findJudge(self, N, trust):
        """
        :type N: int
        :type trust: List[List[int]]
        :rtype: int
        """
        d = [0] * (N+1)
        for a,b in trust:
            d[a] -= 1
            d[b] += 1
        for person in range(1, N + 1):
            if d[person] == N - 1:
                return person
        return -1           	      
		
Copy the code

The results

Given the submission in the Python online submissions. Memory Usage: 10000 ms The submissions in the Python online submissions for Find the Town Judge.Copy the code

Original link: leetcode.com/problems/fi…

Your support is my biggest motivation