comments | difficulty | edit_url | tags | |||
---|---|---|---|---|---|---|
true |
简单 |
|
小镇里有 n
个人,按从 1
到 n
的顺序编号。传言称,这些人中有一个暗地里是小镇法官。
如果小镇法官真的存在,那么:
- 小镇法官不会信任任何人。
- 每个人(除了小镇法官)都信任这位小镇法官。
- 只有一个人同时满足属性 1 和属性 2 。
给你一个数组 trust
,其中 trust[i] = [ai, bi]
表示编号为 ai
的人信任编号为 bi
的人。
如果小镇法官存在并且可以确定他的身份,请返回该法官的编号;否则,返回 -1
。
示例 1:
输入:n = 2, trust = [[1,2]] 输出:2
示例 2:
输入:n = 3, trust = [[1,3],[2,3]] 输出:3
示例 3:
输入:n = 3, trust = [[1,3],[2,3],[3,1]] 输出:-1
提示:
1 <= n <= 1000
0 <= trust.length <= 104
trust[i].length == 2
trust
中的所有trust[i] = [ai, bi]
互不相同ai != bi
1 <= ai, bi <= n
我们创建两个长度为
接下来,我们遍历数组
最后,我们在
时间复杂度
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
cnt1 = [0] * (n + 1)
cnt2 = [0] * (n + 1)
for a, b in trust:
cnt1[a] += 1
cnt2[b] += 1
for i in range(1, n + 1):
if cnt1[i] == 0 and cnt2[i] == n - 1:
return i
return -1
class Solution {
public int findJudge(int n, int[][] trust) {
int[] cnt1 = new int[n + 1];
int[] cnt2 = new int[n + 1];
for (var t : trust) {
int a = t[0], b = t[1];
++cnt1[a];
++cnt2[b];
}
for (int i = 1; i <= n; ++i) {
if (cnt1[i] == 0 && cnt2[i] == n - 1) {
return i;
}
}
return -1;
}
}
class Solution {
public:
int findJudge(int n, vector<vector<int>>& trust) {
vector<int> cnt1(n + 1);
vector<int> cnt2(n + 1);
for (auto& t : trust) {
int a = t[0], b = t[1];
++cnt1[a];
++cnt2[b];
}
for (int i = 1; i <= n; ++i) {
if (cnt1[i] == 0 && cnt2[i] == n - 1) {
return i;
}
}
return -1;
}
};
func findJudge(n int, trust [][]int) int {
cnt1 := make([]int, n+1)
cnt2 := make([]int, n+1)
for _, t := range trust {
a, b := t[0], t[1]
cnt1[a]++
cnt2[b]++
}
for i := 1; i <= n; i++ {
if cnt1[i] == 0 && cnt2[i] == n-1 {
return i
}
}
return -1
}
function findJudge(n: number, trust: number[][]): number {
const cnt1: number[] = new Array(n + 1).fill(0);
const cnt2: number[] = new Array(n + 1).fill(0);
for (const [a, b] of trust) {
++cnt1[a];
++cnt2[b];
}
for (let i = 1; i <= n; ++i) {
if (cnt1[i] === 0 && cnt2[i] === n - 1) {
return i;
}
}
return -1;
}
impl Solution {
pub fn find_judge(n: i32, trust: Vec<Vec<i32>>) -> i32 {
let mut cnt1 = vec![0; (n + 1) as usize];
let mut cnt2 = vec![0; (n + 1) as usize];
for t in trust.iter() {
let a = t[0] as usize;
let b = t[1] as usize;
cnt1[a] += 1;
cnt2[b] += 1;
}
for i in 1..=n as usize {
if cnt1[i] == 0 && cnt2[i] == (n as usize) - 1 {
return i as i32;
}
}
-1
}
}