寻找小镇法官
LeetCode997
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:
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.
思路分析
主要查看两个记录:
法官被信任的次数:应当是小镇人数减一,符合条件的法官只能有一人;
村民投票的次数:法官不能投票人,而其他人至少要投票一次给法官,所以法官投票次数为0,其他人至少为1;
主要是选定数据结构去记录,这里选择用两个数组
上代码
去LeetCode查看原文 代码片
.
public int findJudge(int N, int[][] trust) {
//记录每个人的是否投票
int [] people = new int[N];
//记录每个人被信任为法官的次数
int [] judge = new int[N];
//为上面两个数组赋值
for (int[] i : trust) {
people[i[0]-1]=1;
judge[i[1]-1]++;
}
//标记当前符合条件的法官的下标
//目的是:如果再有符合条件的法官则与题目不符,可以提前结束返回-1
int j = -1;
for (int i = 0; i < people.length; i++) {
if(people[i]!=1&&j==-1&&judge[i]==N-1) {
//判断当前下标是否为第一个法官,如果是,下标赋值给j
j=i;
}else if(j!=-1&&judge[i]==N-1) {
//判断是否是第二个符合条件的法官,如果是,与题目不符,返回-1
return -1;
}else {
continue;
}
}
if(j==-1) {
//判断是否不存在符合条件的法官
return -1;
}else if(judge[j]==N-1) {
//存在一个下标j,使得第j个村民被信任的次数等于全体村民人数-1,
//符合法官的条件,返回下标+1
return j+1;
}else {
//被信任的村民被信任次数不满足条件
return -1;
}
}