[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 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM