Skip to content

Commit babc25c

Browse files
author
Shuo
authored
Merge pull request #476 from openset/develop
Add: Find the Town Judge
2 parents de18ebe + b6e5aff commit babc25c

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package find_the_town_judge
2+
3+
func findJudge(N int, trust [][]int) int {
4+
ans, count := 1, make([]int, N+1)
5+
for _, t := range trust {
6+
count[t[0]] = N
7+
count[t[1]]++
8+
if count[t[1]] == N-1 {
9+
ans = t[1]
10+
}
11+
if ans == t[0] {
12+
ans = -1
13+
}
14+
}
15+
return ans
16+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package find_the_town_judge
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
N int
7+
trust [][]int
8+
expected int
9+
}
10+
11+
func TestFindJudge(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
N: 2,
15+
trust: [][]int{
16+
{1, 2},
17+
},
18+
expected: 2,
19+
},
20+
{
21+
N: 3,
22+
trust: [][]int{
23+
{1, 3},
24+
{2, 3},
25+
},
26+
expected: 3,
27+
},
28+
{
29+
N: 3,
30+
trust: [][]int{
31+
{1, 3},
32+
{2, 3},
33+
{3, 1},
34+
},
35+
expected: -1,
36+
},
37+
{
38+
N: 3,
39+
trust: [][]int{
40+
{1, 2},
41+
{2, 3},
42+
},
43+
expected: -1,
44+
},
45+
{
46+
N: 4,
47+
trust: [][]int{
48+
{1, 3},
49+
{1, 4},
50+
{2, 3},
51+
{2, 4},
52+
{4, 3},
53+
},
54+
expected: 3,
55+
},
56+
{
57+
N: 1,
58+
trust: [][]int{},
59+
expected: 1,
60+
},
61+
}
62+
for _, tc := range tests {
63+
output := findJudge(tc.N, tc.trust)
64+
if output != tc.expected {
65+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.N, tc.trust, output, tc.expected)
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)