Skip to content

Commit 112a580

Browse files
author
Shuo
authored
Merge pull request #646 from openset/develop
Add: 4Sum II
2 parents e4e6fbe + 0484185 commit 112a580

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

problems/4sum-ii/4sum_ii.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,17 @@
11
package p_4sum_ii
2+
3+
func fourSumCount(A []int, B []int, C []int, D []int) int {
4+
ans, n := 0, len(A)
5+
sum := make(map[int]int, n*n)
6+
for i := 0; i < n; i++ {
7+
for j := 0; j < n; j++ {
8+
sum[A[i]+B[j]]++
9+
}
10+
}
11+
for k := 0; k < n; k++ {
12+
for l := 0; l < n; l++ {
13+
ans += sum[-C[k]-D[l]]
14+
}
15+
}
16+
return ans
17+
}

problems/4sum-ii/4sum_ii_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,29 @@
11
package p_4sum_ii
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
a []int
7+
b []int
8+
c []int
9+
d []int
10+
expected int
11+
}
12+
13+
func TestFourSumCount(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
a: []int{1, 2},
17+
b: []int{-2, -1},
18+
c: []int{-1, 2},
19+
d: []int{0, 2},
20+
expected: 2,
21+
},
22+
}
23+
for _, tc := range tests {
24+
output := fourSumCount(tc.a, tc.b, tc.c, tc.d)
25+
if output != tc.expected {
26+
t.Fatalf("input: %v, output: %v, expected: %v", tc, output, tc.expected)
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)