# 【LeetCode】 997. Find the Town Judge ## 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`. > Note: > 1. `1 <= N <= 1000` > 2. `trust.length <= 10000` > 3. `trust[i]` are all different > 4. `trust[i][0] != trust[i][1]` > 5. `1 <= trust[i][0], trust[i][1] <= N` > 在一個小鎮中,有`N`個人分別被標記上`1`到`N`。有一個傳言說這群人中有一個秘密小鎮法官。 > 如果小鎮法官存在,那麼: > 1. 小鎮法官不信任任何人。 > 2. 所有人(除了小鎮法官)相信小鎮法官。 > 3. 剛好有一個人符合第一條和第二條。 > 給你`trust`,一個對子的陣列`trust[i] = [a, b]`代表某個被標記為`a`的人相信某個被標記為`b`的人。 > 如果小鎮法官存在且能夠被證明,回傳小鎮法官的標記。否則回傳`-1`。 > 提示: > 1. `1 <= N <= 1000` > 2. `trust.length <= 10000` > 3. 全部的`trust[i]`都不同 > 4. `trust[i][0] != trust[i][1]` > 5. `1 <= trust[i][0], trust[i][1] <= N` ## Example: ``` 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 ``` ## Solution * 可以將每個人的相信關係想成一個有向圖,我們今天要找到所有節點中,某個節點被其他所有節點指,並且沒有指向任何人。 * 因為測資中不會故意出現重複的關係,我們可以直接計算每個人指出和指入的數量。 * 計算完數量之後,檢查是否存在一個人指出為`0`,指入為`N - 1`,並且為唯一的人。 --- * 這邊有一個小技巧,由於提示4提到不會自己指向自己,且提示3提到關係不會重複,因此`in`最多就是`N - 1`。 * 又由於法官不會指出,我們可以不必多一個變數去存`out`,只要當`i`發生指出的時候,破壞掉`in[i] == N - 1`的可能就好了。 * 最簡單的方法就是指出的時候將`in[i]--`,如此就可以省下一個陣列變數的空間。 ### Code ```C++=1 class Solution { public: int findJudge(int N, vector<vector<int>>& trust) { vector<int> in(N, 0); vector<int> out(N, 0); int ans = -1; for(int i = 0; i < trust.size(); i++) { out[trust[i][0] - 1]++; in[trust[i][1] - 1]++; } for(int i = 0; i < N; i++) { if(out[i] == 0 && in[i] == N - 1) { if(ans == -1) ans = i + 1; else return -1; } } return ans; } }; ``` ```C++=1 class Solution { public: int findJudge(int N, vector<vector<int>>& trust) { vector<int> outAndIn(N, 0); for (int i = 0; i < trust.size(); i++) { outAndIn[trust[i][1] - 1]++; outAndIn[trust[i][0] - 1]--; } for (int i = 0; i < N; i++) { if (outAndIn[i] == N - 1) return i + 1; } return -1; } }; ``` ###### tags: `LeetCode` `C++`