Skip to content

Commit 011dd21

Browse files
author
openset
committed
Add: 4Sum
1 parent 21b0db5 commit 011dd21

File tree

2 files changed

+116
-0
lines changed

2 files changed

+116
-0
lines changed

Diff for: problems/4sum/4sum.go

+36
Original file line numberDiff line numberDiff line change
@@ -1 +1,37 @@
11
package p_4sum
2+
3+
import "sort"
4+
5+
func fourSum(nums []int, target int) [][]int {
6+
sort.Ints(nums)
7+
ans, end := make([][]int, 0), len(nums)-1
8+
for i := 0; i < end-2; i++ {
9+
if i > 0 && nums[i] == nums[i-1] {
10+
continue
11+
}
12+
for j := i + 1; j < end-1; j++ {
13+
if j > i+1 && nums[j] == nums[j-1] {
14+
continue
15+
}
16+
l, r := j+1, end
17+
for l < r {
18+
sum := nums[i] + nums[j] + nums[l] + nums[r]
19+
if sum < target {
20+
l++
21+
} else if sum > target {
22+
r--
23+
} else {
24+
ans = append(ans, []int{nums[i], nums[j], nums[l], nums[r]})
25+
l, r = l+1, r-1
26+
for l < r && nums[l] == nums[l-1] {
27+
l++
28+
}
29+
for l < r && nums[r] == nums[r+1] {
30+
r--
31+
}
32+
}
33+
}
34+
}
35+
}
36+
return ans
37+
}

Diff for: problems/4sum/4sum_test.go

+80
Original file line numberDiff line numberDiff line change
@@ -1 +1,81 @@
11
package p_4sum
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input []int
10+
target int
11+
expected [][]int
12+
}
13+
14+
func TestFourSum(t *testing.T) {
15+
tests := [...]caseType{
16+
{
17+
input: []int{1, 0, -1, 0, -2, 2},
18+
target: 0,
19+
expected: [][]int{
20+
{-2, -1, 1, 2},
21+
{-2, 0, 0, 2},
22+
{-1, 0, 0, 1},
23+
},
24+
},
25+
{
26+
input: []int{-1, 0, 1, 2, -1, -4},
27+
target: 0,
28+
expected: [][]int{
29+
{-1, -1, 0, 2},
30+
},
31+
},
32+
{
33+
input: []int{0, 0, 0, 0},
34+
target: 0,
35+
expected: [][]int{
36+
{0, 0, 0, 0},
37+
},
38+
},
39+
{
40+
input: []int{-2, 0, 0, 2, 2, 2},
41+
target: 0,
42+
expected: [][]int{
43+
{-2, 0, 0, 2},
44+
},
45+
},
46+
{
47+
input: []int{-2, 0, 0, 2, 2, 2, 2},
48+
target: 0,
49+
expected: [][]int{
50+
{-2, 0, 0, 2},
51+
},
52+
},
53+
{
54+
input: []int{-3, -2, -1, 0, 0, 1, 2, 3},
55+
target: 0,
56+
expected: [][]int{
57+
{-3, -2, 2, 3},
58+
{-3, -1, 1, 3},
59+
{-3, 0, 0, 3},
60+
{-3, 0, 1, 2},
61+
{-2, -1, 0, 3},
62+
{-2, -1, 1, 2},
63+
{-2, 0, 0, 2},
64+
{-1, 0, 0, 1},
65+
},
66+
},
67+
{
68+
input: []int{1, -2, -5, -4, -3, 3, 3, 5},
69+
target: -11,
70+
expected: [][]int{
71+
{-5, -4, -3, 1},
72+
},
73+
},
74+
}
75+
for _, tc := range tests {
76+
output := fourSum(tc.input, tc.target)
77+
if !reflect.DeepEqual(output, tc.expected) {
78+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
79+
}
80+
}
81+
}

0 commit comments

Comments
 (0)