Description
In a town, there are n people labeled 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 an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
Examples
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
思路
其实题目给出的town judge的第三个定义是重复的,如果他被n-1个人信任,那必然一个town中只能存在一个judge,否则不符合1/2定义,也就是要么没有town judge,要么只有一个
题目不难(毕竟是easy),但一开始的时候我被《图》的思维束缚住了,所以想的方法是构建一个倒过来的邻接矩阵,也就是从终止节点指向开始节点,这样在一开始的遍历中先找到那些没有出度的点,再在所有没有出度的点中找到入度等于n-1的点
但仔细阅读上面那段话会发现,事情根本没有这么复杂啊!只要计算所有节点的 (入度-出度),让它等于 n-1 就可以了啊!
两个代码都附上,记录一下蠢蠢的思路hhhh
代码
构建邻接矩阵
class Solution {
public int findJudge(int n, int[][] trust) {
List<Integer> peopleWhoTrustNone = new ArrayList<>();
List<List<Integer>> beTrust = new ArrayList<>();
for (int i = 0; i <= n; i++){
peopleWhoTrustNone.add(i);
beTrust.add(new ArrayList<>());
}
for (int[] t: trust){
beTrust.get(t[1]).add(t[0]);
peopleWhoTrustNone.remove(Integer.valueOf(t[0]));
}
if (peopleWhoTrustNone.size() == 1)
return -1;
while (peopleWhoTrustNone.size() > 1){
int candidate = peopleWhoTrustNone.get(1);
if (beTrust.get(candidate).size() == n - 1){
return candidate;
}
peopleWhoTrustNone.remove(1);
}
return -1;
}
}
入度-出度
class Solution {
public int findJudge(int n, int[][] trust) {
int[] trustTimes = new int[n + 1];
for (int[] t: trust){
trustTimes[t[0]] -= 1;
trustTimes[t[1]] += 1;
}
for (int i = 1; i < n + 1; i++){
if (trustTimes[i] == n - 1)
return i;
}
return -1;
}
}