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.
Input: n = 2, trust = [[1,2]]
Output: 2
Input: n = 3, trust = [[1,3],[2,3]]
Output: 3
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
- 마을판사는 모든이들의 신뢰를 받고 자신은 아무도 신뢰하지 않는 사람이다.
- 믿는 사람이 있는 사람의 label 을 a배열에 , 믿음을 받는 사람의 label을 b 배열에 저장한다.
- b 배열의 사람들 중 값이 n-1 (마을판사는 아무도 믿지 않기 때문) 인 인덱스를 찾아서 a 배열에서 그 인덱스의 값이 0이면 인덱스를 리턴
/**
* @param {number} n
* @param {number[][]} trust
* @return {number}
*/
const findJudge = function (n, trust) {
let a = new Array(n).fill(0);
let b = new Array(n).fill(0);
let result = -1;
for (let i = 0; i < trust.length; i++) {
// 믿는 사람이 있는 사람의 label 을 a배열에 , 믿음을 받는 사람의 label을 b 배열에 저장한다.
const [truster, trustee] = trust[i];
a[truster - 1]++;
b[trustee - 1]++;
}
for (let i = 0; i < n; i++) {
if (b[i] === n - 1 && a[i] === 0) {
// trustee 배열에서 값이 n-1인 숫자중 truster 배열에서 값이 0인 index를 찾는다
result = i + 1;
return result;
}
}
return result;
};
