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
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个人,其中有一个法官,我们需要通过人们相互间的信任关系来推断出谁是法官。

小镇上所有的人,除了法官自己,都信任法官,法官不会信任任何人,包括自己。

题目会给出一些信任关系,根据这些关系,我们需要做推断。

这题,我们做下转换,得出每个人分别被多少人信任,再算出每个人分别信任多少人。这样我们遍历这两个结果集,就能知道法官是谁了。

class FindTheTownJudge : public Solution {
public:
    void Execute() {

    }

    int findJudge(int N, vector<vector<int>>& trust) {
        vector<int> trusted_by(N, 0);
        vector<int> trusted(N, 0);

        for (auto &pa : trust) {
            trusted[pa[0] - 1]++;
            trusted_by[pa[1] - 1]++;
        }
        for (std::size_t i = 0; i < trusted_by.size(); i++) {
            if (trusted_by[i] == N - 1 && trusted[i] == 0) {
                return i + 1;
            }
        }
        return -1;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day