mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
0018.四数之和-golang
This commit is contained in:
@ -201,6 +201,54 @@ class Solution(object):
|
|||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
```go
|
||||||
|
func fourSum(nums []int, target int) [][]int {
|
||||||
|
if len(nums) < 4 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
sort.Ints(nums)
|
||||||
|
var res [][]int
|
||||||
|
for i := 0; i < len(nums)-3; i++ {
|
||||||
|
n1 := nums[i]
|
||||||
|
// if n1 > target { // 不能这样写,因为可能是负数
|
||||||
|
// break
|
||||||
|
// }
|
||||||
|
if i > 0 && n1 == nums[i-1] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for j := i + 1; j < len(nums)-2; j++ {
|
||||||
|
n2 := nums[j]
|
||||||
|
if j > i+1 && n2 == nums[j-1] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
l := j + 1
|
||||||
|
r := len(nums) - 1
|
||||||
|
for l < r {
|
||||||
|
n3 := nums[l]
|
||||||
|
n4 := nums[r]
|
||||||
|
sum := n1 + n2 + n3 + n4
|
||||||
|
if sum < target {
|
||||||
|
l++
|
||||||
|
} else if sum > target {
|
||||||
|
r--
|
||||||
|
} else {
|
||||||
|
res = append(res, []int{n1, n2, n3, n4})
|
||||||
|
for l < r && n3 == nums[l+1] { // 去重
|
||||||
|
l++
|
||||||
|
}
|
||||||
|
for l < r && n4 == nums[r-1] { // 去重
|
||||||
|
r--
|
||||||
|
}
|
||||||
|
// 找到答案时,双指针同时靠近
|
||||||
|
r--
|
||||||
|
l++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
javaScript:
|
javaScript:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user