LeetCode-Find the Town Judge

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/89203011

Description:
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:

  1. The town judge trusts nobody.
  2. Everybody (except for the town judge) trusts the town judge.
  3. 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

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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

Note:

  • 1 <= N <= 1000
  • trust.length <= 10000
  • trust[i] are all different
  • trust[i][0] != trust[i][1]
  • 1 <= trust[i][0], trust[i][1] <= N

题意:在小镇上有N个人,其中可能存在一个法官;当且仅当满足以下条件时,J为法官;

  1. 有N-1个人相信J
  2. J不相信任何一个人

解法一:这是一个图的问题,我们以这N个人构建一个有向图,那么我们的目标就是在图中找到一个节点,此节点的入度为N-1(有N-1个人相信)且出度为0(他不相信任何人);第一种做法是先构造一张这样的有向图后,找出是否有节点满足这种要求;

Java
class Solution {
    public int findJudge(int N, int[][] trust) {
        boolean[][] mark = new boolean[N][N];
        for (int i = 0; i != trust.length; i++) {
            mark[trust[i][0] - 1][trust[i][1] - 1] = true;
        }
        for (int i = 0; i != mark[0].length; ++i) {
            int cnt = 0;
            for (int j = 0; j < mark.length; j++) {
                cnt = mark[j][i] ? cnt + 1 : cnt;
            }
            if (cnt == N - 1) {
                boolean get = true;
                for (int k = 0; k != mark.length; k++) {
                    if (mark[i][k]) {
                        get = false;
                        break;
                    }
                }
                if (get) {
                    return i + 1;
                }
            }
        }
        
        return -1;
    }
}

解法二:其实,我们只需要统计每个节点的入度与出度的差即可;如果存在法官,那么此节点必定满足入度 - 出度 = N - 1;因此,我们只需要统计每个节点入度与出度之差即可;

Java
class Solution {
    public int findJudge(int N, int[][] trust) {
        int[] cnt = new int[N];
        for (int[] t: trust) {
            cnt[t[0] - 1]--; //out
            cnt[t[1] - 1]++; //in
        }
        for (int i = 0; i != N; ++i) {
            if (cnt[i] == N - 1) {
                return i + 1;
            }
        }
        
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/89203011