[LeetCode] 997. Find the Town Judge 找出小镇法官


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

Constraints:

  • 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] <= N

这道题是说是有N个人,里面有一个小镇法官,要求是法官不相信任何人,而其他所有人都信任法官,现在让我们找出这个法官,不存在的话返回 -1。跟之前那道
Find the Celebrity 非常相似,那道题是所有人都认识名人,但是名人不认识任何人。而这里是法官不相信人任何人,而所有人都相信法官,不同的是在于给的数据结构不同,名人那道是给了个 API 判断是否认识,而这里给了个信任数组,那么解法就稍有不同了。由于信任是有方向的,所以是一个有向图,因为法官不相信任何人,所以其没有出度,而所有人都信任他,则入度满值。最简单直接的方法就是统计每个结点的出度和入度,然后找出那个出度为0,入度为 N-1 的结点即可,参见代码如下:


解法一:

class Solution {
public:
    int findJudge(int N, vector<vector<int>>& trust) {
		vector<int> in(N + 1), out(N + 1);
		for (auto a : trust) {
			++out[a[0]];
			++in[a[1]];
		}
		for (int i = 1; i <= N; ++i) {
			if (in[i] == N - 1 && out[i] == 0) return i;
		}
		return -1;
    }
};

若没有想出有向图出度和入度的解法,也可以使用下面这种方法,思路是这样的,由于法官是不会相信任何人的,所以前一个位置的人肯定不是法官,则用一个 HashSet 来保存所有会相信别人的人,然后再用一个 HashMap 来建立某个人和信任该人的所有人的集合,那么只要找出不在 HashSet 中的人,且有 N-1 个人信任他,则该人一定是法官,其实本质上跟上面的解法还是一样的,参见代码如下:


解法二:

class Solution {
public:
    int findJudge(int N, vector<vector<int>>& trust) {
        unordered_set<int> st;
        unordered_map<int, vector<int>> beTrustedMap;
        for (auto &a : trust) {
            st.insert(a[0]);
            beTrustedMap[a[1]].push_back(a[0]);
        }
        for (int i = 1; i <= N; ++i) {
            if (st.count(i)) continue;
            if (beTrustedMap[i].size() == N - 1) return i;
        }
        return -1;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/997


类似题目:

Find the Celebrity


参考资料:

https://leetcode.com/problems/find-the-town-judge/

https://leetcode.com/problems/find-the-town-judge/discuss/242938/JavaC%2B%2BPython-Directed-Graph


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2021-01-12 12:47  Grandyang  阅读(1277)  评论(0编辑  收藏  举报
Fork me on GitHub