寻找小镇法官

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;
   	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值