Skip to content

Commit 7dbb23d

Browse files
committed
Add 18. 4Sum
1 parent 3c5f54c commit 7dbb23d

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

medium/18_4sum/18_4sum.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package four_sum
2+
3+
import "sort"
4+
5+
func fourSum(nums []int, target int) [][]int {
6+
res := make([][]int, 0)
7+
sort.Ints(nums) // Sort arr in asc order
8+
9+
for i := 0; i < len(nums); i++ {
10+
if i > 0 && nums[i] == nums[i - 1] { // remove duplicatefor i
11+
continue
12+
}
13+
for j := i + 1; j < len(nums); j++ {
14+
if j > i + 1 && nums[j] == nums[j - 1] { // remove duplicatefor j
15+
continue
16+
}
17+
l := j + 1
18+
r := len(nums) - 1
19+
for l < r {
20+
if nums[i] + nums[j] + nums[l] + nums[r] == target {
21+
res = append(res, []int{nums[i], nums[j], nums[l], nums[r]})
22+
23+
for l < r && nums[l] == nums[l + 1] {
24+
l ++
25+
}
26+
for l < r && nums[r] == nums[r - 1] {
27+
r --
28+
}
29+
l ++
30+
r --
31+
} else if nums[i] + nums[j] + nums[l] + nums[r] > target {
32+
r --
33+
} else {
34+
l ++
35+
}
36+
}
37+
}
38+
}
39+
return res
40+
}

medium/18_4sum/18_4sum_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package four_sum
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type Problem struct {
9+
name string
10+
nums []int
11+
target int
12+
expectedResult [][]int
13+
}
14+
15+
func TestFourSum(t *testing.T) {
16+
tests := []Problem {
17+
{
18+
name: "Test Case 1",
19+
nums: []int{1,0,-1,0,-2,2},
20+
target: 0,
21+
expectedResult: [][]int{{-2,-1,1,2},{-2,0,0,2},{-1,0,0,1}},
22+
},
23+
{
24+
name: "Test Case 1",
25+
nums: []int{1,0,-1,0,-2,2},
26+
target: 0,
27+
expectedResult: [][]int{{-2,-1,1,2},{-2,0,0,2},{-1,0,0,1}},
28+
},
29+
}
30+
31+
for _, test := range tests {
32+
got := fourSum(test.nums, test.target)
33+
34+
if !reflect.DeepEqual(got, test.expectedResult) {
35+
t.Errorf("fourSum(%v, %d) = %v, want = %v", test.nums, test.target, got, test.expectedResult)
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)