Skip to content

Commit 4068040

Browse files
authored
0018.四数之和-golang
1 parent 5e575eb commit 4068040

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

problems/0018.四数之和.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,54 @@ class Solution(object):
201201
```
202202

203203
Go:
204+
```go
205+
func fourSum(nums []int, target int) [][]int {
206+
if len(nums) < 4 {
207+
return nil
208+
}
209+
sort.Ints(nums)
210+
var res [][]int
211+
for i := 0; i < len(nums)-3; i++ {
212+
n1 := nums[i]
213+
// if n1 > target { // 不能这样写,因为可能是负数
214+
// break
215+
// }
216+
if i > 0 && n1 == nums[i-1] {
217+
continue
218+
}
219+
for j := i + 1; j < len(nums)-2; j++ {
220+
n2 := nums[j]
221+
if j > i+1 && n2 == nums[j-1] {
222+
continue
223+
}
224+
l := j + 1
225+
r := len(nums) - 1
226+
for l < r {
227+
n3 := nums[l]
228+
n4 := nums[r]
229+
sum := n1 + n2 + n3 + n4
230+
if sum < target {
231+
l++
232+
} else if sum > target {
233+
r--
234+
} else {
235+
res = append(res, []int{n1, n2, n3, n4})
236+
for l < r && n3 == nums[l+1] { // 去重
237+
l++
238+
}
239+
for l < r && n4 == nums[r-1] { // 去重
240+
r--
241+
}
242+
// 找到答案时,双指针同时靠近
243+
r--
244+
l++
245+
}
246+
}
247+
}
248+
}
249+
return res
250+
}
251+
```
204252

205253
javaScript:
206254

0 commit comments

Comments
 (0)