-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpt_solution.js
59 lines (48 loc) · 1.18 KB
/
gpt_solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* @param {number} n
* @param {number[][]} trust
* @return {number}
*/
function findJudge(n, trust) {
const inDegree = Array(n + 1).fill(0); // point in -> being trust
const outDegree = Array(n + 1).fill(0); // point out -> trust someonme
console.log(inDegree)
console.log(outDegree)
for (const [a, b] of trust) {
outDegree[a]++;
inDegree[b]++;
}
console.log(inDegree)
console.log(outDegree)
for (let i = 1; i <= n; i++) {
if (inDegree[i] === n - 1 && outDegree[i] === 0) {
return i;
}
}
return -1;
}
// I found this smarter also better in terms of memory.
function findJudge2(n, trust) {
const trustCounts = Array(n + 1).fill(0);
for (const [a, b] of trust) {
trustCounts[a]--;
trustCounts[b]++;
}
for (let i = 1; i <= n; i++) {
if (trustCounts[i] === n - 1) {
return i;
}
}
return -1;
}
// let x = findJudge(2, [[1, 2]]) // 2
// let x = findJudge(4, [[1, 2], [1, 3], [2, 1], [2, 3], [1, 4], [4, 3], [4, 1]]) // 3
// let x = findJudge(1, [])
// let x = findJudge(3, [[1, 2], [2, 3]]) // -1
let x = findJudge(3, [[1, 3], [2, 3], [3, 1]]) // -1
// 1 2 3
// 1 -> 3
// 2 -> 3
// 3 -> 1
console.log("x")
console.log(x)