Skip to content

Commit 9fe9ee5

Browse files
aQuaaQua
aQua
authored and
aQua
committed
adding Problem 18
1 parent c5e88ee commit 9fe9ee5

File tree

3 files changed

+50
-7
lines changed

3 files changed

+50
-7
lines changed

Algorithms/0018.4sum/4sum.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,29 @@
11
package Problem0018
22

3+
import (
4+
"sort"
5+
)
6+
7+
func fourSum(nums []int, target int) [][]int {
8+
res := [][]int{}
9+
sort.Ints(nums)
10+
11+
for i := 0; i < len(nums)-3; i++ {
12+
for j := i + 1; j < len(nums)-2; j++ {
13+
l, r := j+1, len(nums)-1
14+
for l < r {
15+
16+
s := nums[i] + nums[j] + nums[l] + nums[r]
17+
switch {
18+
case s < target:
19+
l++
20+
case s > target:
21+
r--
22+
default:
23+
}
24+
}
25+
}
26+
27+
}
28+
return res
29+
}

Algorithms/0018.4sum/4sum_test.go

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0018
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -15,13 +15,14 @@ type question struct {
1515
// para 是参数
1616
// one 代表第一个参数
1717
type para struct {
18-
one string
18+
one []int
19+
two int
1920
}
2021

2122
// ans 是答案
2223
// one 代表第一个答案
2324
type ans struct {
24-
one string
25+
one [][]int
2526
}
2627

2728
func Test_Problem0018(t *testing.T) {
@@ -30,17 +31,21 @@ func Test_Problem0018(t *testing.T) {
3031
qs := []question{
3132

3233
question{
33-
para{""},
34-
ans{""},
34+
para{[]int{1, 0, -1, 0, -2, 2}, 0},
35+
ans{[][]int{
36+
[]int{-1, 0, 0, 1},
37+
[]int{-2, -1, 1, 2},
38+
[]int{-2, 0, 0, 2},
39+
}},
3540
},
36-
41+
3742
// 如需多个测试,可以复制上方元素。
3843
}
3944

4045
for _, q := range qs {
4146
a, p := q.ans, q.para
4247
fmt.Printf("~~%v~~\n", p)
4348

44-
ast.Equal(a.one, (p.one), "输入:%v", p)
49+
ast.Equal(a.one, fourSum(p.one, p.two), "输入:%v", p)
4550
}
4651
}

Algorithms/0018.4sum/README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
11
# [18. 4Sum](https://leetcode.com/problems/4sum/)
22

33
## 题目
4+
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
45

6+
Note: The solution set must not contain duplicate quadruplets.
7+
```
8+
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
59
10+
A solution set is:
11+
[
12+
[-1, 0, 0, 1],
13+
[-2, -1, 1, 2],
14+
[-2, 0, 0, 2]
15+
]
16+
```
617
## 解题思路
718

819

0 commit comments

Comments
 (0)