Skip to content

Commit 2a1b615

Browse files
aQuaaQua
aQua
authored and
aQua
committed
添加了穷举法额解法,但是超时了。
1 parent e04f909 commit 2a1b615

File tree

3 files changed

+58
-10
lines changed

3 files changed

+58
-10
lines changed

Algorithms/0015.3sum/3sum.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,47 @@
11
package Problem0015
22

3+
import (
4+
"sort"
5+
)
6+
7+
func threeSum(nums []int) [][]int {
8+
res := [][]int{}
9+
10+
for i := 0; i < len(nums)-2; i++ {
11+
for j := i + 1; j < len(nums)-1; j++ {
12+
for k := j + 1; k < len(nums); k++ {
13+
if nums[i]+nums[j]+nums[k] == 0 {
14+
temp := []int{nums[i], nums[j], nums[k]}
15+
if yes := contain(res, temp); !yes {
16+
res = append(res, temp)
17+
18+
}
19+
}
20+
}
21+
}
22+
}
23+
24+
return res
25+
}
26+
27+
func contain(numss [][]int, nums []int) bool {
28+
sort.Ints(nums)
29+
30+
for _, ns := range numss {
31+
sort.Ints(ns)
32+
if equal(ns, nums) {
33+
return true
34+
}
35+
}
36+
37+
return false
38+
}
39+
40+
func equal(a, b []int) bool {
41+
for i, v := range a {
42+
if v != b[i] {
43+
return false
44+
}
45+
}
46+
return true
47+
}

Algorithms/0015.3sum/3sum_test.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@ type question struct {
1414
// para 是参数
1515
// one 代表第一个参数
1616
type para struct {
17-
one string
17+
one []int
1818
}
1919

2020
// ans 是答案
2121
// one 代表第一个答案
2222
type ans struct {
23-
one string
23+
one [][]int
2424
}
2525

2626
func Test_Problem0015(t *testing.T) {
@@ -29,16 +29,19 @@ func Test_Problem0015(t *testing.T) {
2929
qs := []question{
3030

3131
question{
32-
para{""},
33-
ans{""},
32+
para{[]int{-1, 0, 1, 2, -1, -4}},
33+
ans{[][]int{
34+
[]int{-1, 0, 1},
35+
[]int{-1, -1, 2},
36+
}},
3437
},
35-
38+
3639
// 如需多个测试,可以复制上方元素。
3740
}
3841

3942
for _, q := range qs {
4043
a, p := q.ans, q.para
41-
42-
ast.Equal(a.one, p.one, "输入:%v", p)
44+
45+
ast.Equal(a.one, threeSum(p.one), "输入:%v", p)
4346
}
4447
}

Algorithms/0016.3sum-closest/3sum-closest_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,13 @@ func Test_Problem0016(t *testing.T) {
3232
para{""},
3333
ans{""},
3434
},
35-
35+
3636
// 如需多个测试,可以复制上方元素。
3737
}
3838

3939
for _, q := range qs {
4040
a, p := q.ans, q.para
41-
42-
ast.Equal(a.one, p.one, "输入:%v", p)
41+
42+
ast.Equal(a.one, (p.one), "输入:%v", p)
4343
}
4444
}

0 commit comments

Comments
 (0)