-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-the-town-judge.java
72 lines (68 loc) · 1.71 KB
/
find-the-town-judge.java
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
60
61
62
63
64
65
66
67
68
69
70
71
72
// BEATS 55$
// CPP CODE
// class Solution {
// public:
// int findJudge(int n, vector<vector<int>>& trust) {
// // The town judge trusts nobody.
// // Everybody (except for the town judge) trusts the town judge.
// vector<int> trusting (n+1,0);
// vector<int> trusted (n+1,0);
// for(auto i: trust){
// trusting[i[0]]++;
// trusted[i[1]]++;
// }
// int ans=-1;
// for(int i=1;i<=n;i++){
// if(trusting[i]==0 && trusted[i]==n-1){
// ans=i;
// }
// }
// return ans;
// }
// };
// RUN TIME 2MS BEATS 99.85%
// JAVA SOLUTION
class Solution {
public int findJudge(int n, int[][] trust) {
int ans[]=new int[n+1];
for(int i=0;i<trust.length;i++){
ans[trust[i][0]]++;
}
int i=1;
for(i=1;i<n+1;i++){
if(ans[i]==0){
break;
}
}
int count=0;
for(int j=0;j<trust.length;j++){
if(trust[j][1]==i){
count++;
}
}
if(count==n-1){
return i;
}
else{
return -1;
}
}
}
//alternate solution
// class Solution {
// public int findJudge(int n, int[][] trust) {
// int ans[] = new int[n+1];
// for(int[] relation : trust){
// int trusting = relation[0];
// int trusted= relation[1];
// ans[trusting]--;
// ans[trusted]++;
// }
// for(int i=1;i<=n;i++){
// if(ans[i]==n-1){
// return i;
// }
// }
// return -1;
// }
// }