LeetCode
每日一题 997. 找到小镇的法官
https://leetcode-cn.com/problems/find-the-town-judge/
分析
- 数据以1 ~ n 排序
- n = 5 -> 1 2 3 5 如果都相信 4 , 4 都不相信其他人则为法官
- 法官不信任任何人
- 任何人都相信法官
- 信任法官的人数为 n - 1 人 -> 法官不信任自己
- 法官不信任任何人[0] -> 0
class Solution {
public int findJudge(int N, int[][] trust) {
int [][]human = new int [N][2];
for (int people[] : trust){
int in = people[0];
// 相信的人
int out = people [1];
// 被相信的人
human[in - 1][0] ++;
human[out - 1][1] ++;
}
for (int i = 0; i < N; i++){
if(human[i][0] == 0 && human[i][1] == N - 1)
// 法官被所有人信任,当自己不信任 N - 1
return i + 1;
}
return -1;
}
}
其中不能用,读取每一个 trust
的数据,因为法官不信任任何人,不存在
// for (int i = 0; i < N; i++){
// int in = trust[i][0];
// int out = trust[i][1];
// human[in - 1][0] ++;
// human[out - 1][1] ++;
// }
<++>