Skip to content

Commit 0811263

Browse files
aQuaaQua
aQua
authored and
aQua
committed
added Problem 18
1 parent c57f0a8 commit 0811263

File tree

4 files changed

+38
-7
lines changed

4 files changed

+38
-7
lines changed

Algorithms/0015.3sum/3sum.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ func threeSum(nums []int) [][]int {
99

1010
for i := range nums {
1111
// 避免添加重复的结果
12+
// i>0 是为了防止nums[i-1]溢出
1213
if i > 0 && nums[i] == nums[i-1] {
1314
continue
1415
}

Algorithms/0018.4sum/4sum.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,16 @@ func fourSum(nums []int, target int) [][]int {
1010

1111
for i := 0; i < len(nums)-3; i++ {
1212
// 避免添加重复的结果
13-
if i > 1 && nums[i] == nums[i-2] {
13+
// i>0 是为了防止nums[i-1]溢出
14+
if i > 0 && nums[i] == nums[i-1] {
1415
continue
1516
}
1617

1718
for j := i + 1; j < len(nums)-2; j++ {
1819
// 避免添加重复的结果
19-
if nums[j] == nums[j-1] {
20+
// nums[j-1]虽然不会溢出
21+
// 但是不添加 j > i+1 的话,会漏掉那些i和j为相同数值的答案
22+
if j > i+1 && nums[j] == nums[j-1] {
2023
continue
2124
}
2225

@@ -49,8 +52,9 @@ func next(nums []int, l, r int) (int, int) {
4952
default:
5053
l++
5154
r--
52-
break
55+
return l, r
5356
}
5457
}
58+
5559
return l, r
5660
}

Algorithms/0018.4sum/4sum_test.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,13 @@ func Test_Problem0018(t *testing.T) {
5757
[]int{0, 0, 0, 0},
5858
}},
5959
},
60-
60+
question{
61+
para{[]int{0, -1, 0, 1, -2, -5, 3, 5, 0}, 6},
62+
ans{[][]int{
63+
[]int{-2, 0, 3, 5},
64+
[]int{0, 0, 1, 5},
65+
}},
66+
},
6167
// 如需多个测试,可以复制上方元素。
6268
}
6369

@@ -66,5 +72,26 @@ func Test_Problem0018(t *testing.T) {
6672
fmt.Printf("~~%v~~\n", p)
6773

6874
ast.Equal(a.one, fourSum(p.one, p.two), "输入:%v", p)
75+
printIntss(a.one, fourSum(p.one, p.two))
76+
}
77+
}
78+
79+
func printIntss(e, a [][]int) {
80+
fmt.Println("expected \tactual")
81+
l := len(e)
82+
if l < len(a) {
83+
l = len(a)
84+
}
85+
for i := 0; i < l; i++ {
86+
if i < len(e) {
87+
fmt.Print(e[i], "\t")
88+
} else {
89+
fmt.Print("\t\t")
90+
}
91+
92+
if i < len(a) {
93+
fmt.Print(a[i])
94+
}
95+
fmt.Println()
6996
}
7097
}

Algorithms/0018.4sum/README.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@ A solution set is:
1515
]
1616
```
1717
## 解题思路
18-
18+
我解答这一题的思路,和[15. 3Sum](./Algorithms/0015.3sum)的思路一样的,就是多套了一层循环而已。
1919

2020
## 总结
21-
22-
21+
未知的问题,可以转换成已知的问题来求解。

0 commit comments

Comments
 (0)